objective-C如何声明私有财产的类别?

时间:2014-08-25 20:02:08

标签: ios objective-c private objective-c-category

我是Objective-C的新手,如果在某个地方重复,请道歉。我有一个类别(?),如:

SomeClass.h内:

@interface SomeClass (SomeCategory) <SomeDelegate>
@property (nonatomic, retain) id somePublicProperty;
@property (nonatomic, retain) id someProperty; // <-- i want to move this to "private"
@end

现在我的SomeClass.m,我所拥有的只是:

@implementation SomeClass (SomeCategory)

// dynamic setters/getters here for someProperty.

@end

我认为someProperty是公开的。我怎么做这个&#34;私人&#34;? (换句话说,我如何在.m文件中将其语法化?我试图使用

@interface SomeClass (SomeCategory) {
    @property (nonatomic, retain) somePrivateProperty;
} 
@end

但它只是抱怨我有类别的重复定义。我该如何正确地做到这一点?

3 个答案:

答案 0 :(得分:7)

.h文件中,您不应该提供该类别。只需使用:

@interface SomeClass : SomeBaseClass < SomeDelegate>
    @property (nonatomic, retain) id somePublicProperty;
@end

在您的.m文件中,在 class extension 中定义您的私有资产:

@interface SomeClass ()
    @property (nonatomic, retain) id somePrivateProperty;
@end

类扩展不是类似的类,因为它允许您扩展接口以及向您的类添加新存储。

在班级类别you can define new properties, but no storage will be allocated for it中,您必须手动执行此操作:

@interface SomeClass (SomeBaseCategory)
    @property (nonatomic, retain) id somePrivateProperty;
@end

@implementation SomeClass {
    id _somePrivateProperty;
}

    - (void)setSomePrivateProperty:(id)property {

        _somePrivateProperty = property;
    }

    - (id)somePrivateProperty {
         return _somePrivateProperty;
    }

@end

否则您的应用会崩溃。

在任何情况下,请记住,鉴于Objective-C的动态特性,您的属性永远不会完全私有,因为您始终可以通过objc_msgsend向Objective-C对象发送消息,从而设置或阅读物业价值。

编辑:

如果您没有类实现的源代码,则无法定义类扩展(根据上面链接的源)。

在这种情况下,you could use object association to define properties

答案 1 :(得分:2)

只需在实现块外的.m文件中添加类别定义

像这样:

@interface MyClass (MyCategory)
@property (assign) BOOL myPrivateProperty;
@end

@implementation MyClass
...
@end

答案 2 :(得分:0)

类别最适合用于为您不拥有且无法更改的代码添加功能。通过类别添加属性并非不可能,但要困难得多。

类扩展最适合用于保存对象所需的属性,但不是公开的。

如果确实需要为此对象添加属性,那么使用Objective-C运行时关联对象

的方法就是这样做

有关何时/如何使用here

的精彩文章
相关问题