Objective c 生成类成员属性并合成它们

Objective c 生成类成员属性并合成它们,objective-c,cocoa,cocoa-touch,Objective C,Cocoa,Cocoa Touch,可以肯定地说,如果类成员不需要getter或setter函数,那么将它们设置为属性并合成它们就没有意义了吗?嗯,是的,但是属性通常对实现本身很有帮助,即使属性不会在实现之外设置 例如,假设您有 @interface SomeObject : NSObject { NSThing *thing; } @end @implementation SomeObject - (id)init { if((self = [super init])) thing = [[N

可以肯定地说,如果类成员不需要getter或setter函数,那么将它们设置为属性并合成它们就没有意义了吗?

嗯,是的,但是属性通常对实现本身很有帮助,即使属性不会在实现之外设置

例如,假设您有

@interface SomeObject : NSObject {
    NSThing *thing;
}
@end

@implementation SomeObject

- (id)init {
    if((self = [super init]))
        thing = [[NSThing someThing] retain];
    return self;
}

- (void)someMethod {
    if(thing)
        [thing release];
    thing = [[NSThing someOtherThing] retain];
}

// etc etc

@end
你为什么要费心检查
东西
是否已分配,释放
东西
,将其设置为其他东西,然后再
保留
它,而你可以简单地执行以下操作:

- (id)init {
    if((self = [super init]))
        [self setThing:[NSThing someThing]];
    return self;
}

- (void)someMethod {
    [self setThing:[NSThing someOtherThing]];
}
如果不希望在类之外访问这些属性,可以使用类别

@interface SomeObject ()
@property (retain) NSThing *thing;
@end

<>在.Objy.C中,你没有问C++吗?如果不是,你在问什么?我是说你在.h文件中@interface之后声明的东西。如果它们不是类成员,那么它们被称为什么,接口成员?实例变量。您应该阅读Objective-C编程语言文档:它实际上被称为类扩展。一个类别应该有一个单独的接口和一个单独的实现(虽然编译器目前允许您不使用单独的实现),但类扩展只是类主接口的延续,因此它声明的方法必须在类的主实现中实现,与类的实际主接口中声明的任何方法相同。此外,通常不应在
init
方法和
dealloc
方法中使用访问器。如果定义自定义访问器,或子类重写访问器,则在半初始化/半解除分配的对象上使用该访问器可能不安全。您应该在类中的任何其他地方使用访问器,但是应该在
init
方法和
dealloc
中避免使用它们。