How can I declare a private property within a named category?

故事扮演 提交于 2019-12-20 12:28:35

问题


I know about the possibility of declaring private properties on a class by putting them inside an unnamed category on that class declared in the implementation (.m) file of that class. That's not what I want to do.

I'm dealing with a named category on a class that adds some functionality to that class. For this functionality, it would help me very much to have a private property to use in my category - so the usual way of achieving this (described above) doesn't seem to work for me. Or does it? Please enlighten me!


回答1:


Inside your category's implementation file, declare another category and call it something like MyCategoryName_Private, and declare your private properties there. Provide implementations of the -propertyName and -setPropertyName: methods using associated objects.

For example, your implementation file might look like this:

#import "SomeClass+MyCategory.h"
#import <objc/runtime.h>

@interface SomeClass (MyCategory_Private)

@property (nonatomic, strong) id somePrivateProperty;

@end

@implementation SomeClass (MyCategory_Private)

static void *AssociationKey;

- (id)somePrivateProperty 
{
    return objc_getAssociatedObject(self, AssociationKey);
}

- (void)setSomePrivateProperty:(id)arg
{
    objc_setAssociatedObject(self, AssociationKey, arg, OBJC_ASSOCIATION_RETAIN);
}

@end

@implementation SomeClass (MyCategory)

// implement your publicly declared category methods

@end


来源:https://stackoverflow.com/questions/14399991/how-can-i-declare-a-private-property-within-a-named-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!