#import @interface Person :NSObject { int age; NSString * name; } -(void)setAge:(int)age; -(void) sayHi; @end @implementation Person -(void)setAge:(int)age{ self.age=age; } -(void)sayHi{ NSLog(@"im jerry %d",age); } @end int main(int argc, const char * argv[]) { @autoreleasepool { Person* p=[Person new]; [p setAge:5]; [p sayHi]; } return 0; }
self.age=age;
这里报错了。
在java里面,不是this.age=age吗?oc里面难道不行吗?
In objective-c, although the attribute is called as a simple assignment and value operation, in fact, the use of the attribute is a method call!
For example:
@property(copy) NSMutableArray *array;
After this attribute is added, it looks like a variable. In fact, the compiler does more than just add a variable:
Added a class global variable NSMutableArray * _array
Added Get method-(NSMutableArray *)array;
Added Set method-(void)setArray:(NSMutableArray *)array;
Although
@property
,指定属性,但是缺命名了一个符合属性的set
方法的方法名,因此,使用时一样可以使用点语法
is not used in your code.A
B
A and B are equivalent! After compilation, A will be converted into the form of B, and B will be further converted into the form of C function call!
You are here
-setAge:
方法里面调用-setAge:
,导致无限递归。如果你有注意到崩溃时程序的栈,会发现栈里面都是-setAge:
.If you want to avoid this problem, just use class variable assignment directly
The detailed explanation is as mentioned above, in short:
The dot syntax in OC is just a compiler feature, and the essence is still method calling.
Don’t use dot syntax here, and put an underscore in front of your member variables to distinguish them. _age = age;
Written here @interface can be used directly without adding self.
Just age = age