Home  >  Q&A  >  body text

objective-c - 为什么这一段Objectc会报错?



#import <Foundation/Foundation.h>


@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里面难道不行吗?

阿神阿神2709 days ago688

reply all(4)I'll reply

  • 大家讲道理

    大家讲道理2017-04-24 09:15:51

    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;

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-24 09:15:51

    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.

    reply
    0
  • 高洛峰

    高洛峰2017-04-24 09:15:51

    Don’t use dot syntax here, and put an underscore in front of your member variables to distinguish them. _age = age;

    reply
    0
  • 怪我咯

    怪我咯2017-04-24 09:15:51

    Written here @interface can be used directly without adding self.
    Just age = age

    reply
    0
  • Cancelreply