objective-c - iOS 中setter和getter方法为什么不可以同时写
迷茫
迷茫 2017-04-17 14:43:19
0
5
235

单独写setter方法或者getter方法不会报错。

但是同时写,会报错,说不认识成员变量。

例如属性 NSString * name;

-(void)setName:(NSString *)name
{
_name = name;
}

-(NSString *)name
{
return _name;
}

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(5)
黄舟

objective-cIf both getter and setter of a certain attribute need to be rewritten
Need to add @synthesize propertyName = _propertyName;
As for why there are many detailed article analyzes on the Internet, you can check it out

伊谢尔伦

If you rewrite the getter and setter methods at the same time, the system will not automatically generate this member variable for you, so of course an error will be reported saying that this member variable is not recognized. First manually generate member variables, and then rewrite the getter and setter methods at the same time.

BOOL _carOwner;

#pragma mark - getters and setters
-(void)setCarOwner:(BOOL)carOwner
{   
    _carOwner = carOwner;

    // 自定义操作
    [[NSUserDefaults standardUserDefaults] setBool:_carOwner forKey:@"KeyIsCarOwner"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (BOOL)carOwner {

    // 自定义操作
    id result = [[NSUserDefaults standardUserDefaults] valueForKey:@"KeyIsCarOwner"];
    if (result) {
        return [[[NSUserDefaults standardUserDefaults] valueForKey:@"KeyIsCarOwner"] boolValue];

    }
    return _carOwner;
}

刘奇

Because you wrote it wrong. (:з ∠) is written as self-> name = name;

PHPzhong

I just tried it and it’s exactly what you said. Don't know why. After adding @synthesize name = _name; syntax, no error will be reported.

左手右手慢动作

Just use self.name, the effect is the same anyway

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!