objective-c - 为什么这一段Objectc会报错?
阿神
阿神 2017-04-24 09:13:51
0
4
665
#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里面难道不行吗?

阿神
阿神

闭关修行中......

reply all (4)
大家讲道理

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:

  1. Added a class global variable NSMutableArray * _array

  2. Added Get method-(NSMutableArray *)array;

  3. Added Set method-(void)setArray:(NSMutableArray *)array;

Although@property,指定属性,但是缺命名了一个符合属性的set方法的方法名,因此,使用时一样可以使用点语法is not used in your code.

A

self.age=age;

B

[self setAge:age];

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

_age = age;
    Peter_Zhu

    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

          Latest Downloads
          More>
          Web Effects
          Website Source Code
          Website Materials
          Front End Template
          About us Disclaimer Sitemap
          php.cn:Public welfare online PHP training,Help PHP learners grow quickly!