如何在命名类别中声明私有属性? [英] How can I declare a private property within a named category?

查看:80
本文介绍了如何在命名类别中声明私有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以通过将私有属性放在该类的实现 (.m) 文件中声明的该类的未命名类别中来声明该类的私有属性.那不是我想做的.

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!

推荐答案

在您的类别的实现文件中,声明另一个类别并将其命名为类似 MyCategoryName_Private 的名称,并在那里声明您的私有属性.使用关联对象提供 -propertyName-setPropertyName: 方法的实现.

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

这篇关于如何在命名类别中声明私有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆