简体   繁体   English

声明没有实例变量的属性

[英]Declaring a property with no instance variable

由于Xcode现在自动添加@synthesis,如何在没有相应的ivar的情况下声明属性?

您需要实现getter和setter,然后它将不会自动合成并自动创建ivar。

@interface Obj : NSObject
@property NSString* str;
@end

@implementation

-(NSString*) str {
    //TODO:
    return @"sdfsdf";
}

-(void) setStr:(NSString*) st {
//TODO:
}

@end

Naming convention is simple: 命名约定很简单:

getter has the same name as the property (in example it is str), setter must have set prefix, ie setPropertyName (first letter of property name is uppercase: setStr:) getter与属性同名(例如str),setter必须有set前缀,即setPropertyName(属性名的第一个字母是大写:setStr :)

You can also add attributes like atomic, retain, strong etc. but they will have no effect in case you're implementing properties yourself, but it's a good hint for the users of your class. 您还可以添加像atomic,retain,strong等属性,但是如果您自己实现属性,它们将无效,但这对您的类用户来说是一个很好的提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM