在Objective-C中点的意义与Java中的大不相同
OC中
//接口
@interface Person : NSObject{
int _age ;
}
- (int) age;
- (void) setAge:(int)age;
- (id) initWithAge:(int) age;
@end
//实现类
@implementation Person
-(int) age{
return _age;
}
-(void) setAge:(int)age{
_age = age;
}
- (void)initWithAge:(int)age{
self = [self init];
if(self){ //和if(self !=nil )一样
_age = age;
}
}
@end
在main方法调用这个对象的时候:
Person * person = [[Person alloc] init];
person.age = 10; //和 [person setAge:10] 相同
int age = person.age;
NSLog(@"%i" , age);
NSLog(@"%@" , stu); //打印对象信息,显示为<Person:16位内存地址>
1、点语法解读:
int age = person.age;这句是调用person对象的属性age的get方法,和int age = [person age];一样
我们在set方法中之所以不能用self.age = age;这种写法是因为,这种方法是调用person的set方法。
2、构造方法解读:
在重写构造方法之后,在main方法中调用:
Person * person = [[Person alloc] initWithAge:20];
3、打印对象信息:
NSLog(@"%@" , stu);
"%@" :打印对象信息