如何通过类别扩展向 NSMutableArray 添加属性?
我知道我可以使用“类别扩展”(即 @interface NSMutableArray (MyExtension))对 NSMutableArray 进行“子类化”,以向该类添加新函数。但是,有没有办法使用类别扩展来向扩展添加新的属性?
I know that I can "subclass" an NSMutableArray using "category extensions," i.e. @interface NSMutableArray (MyExtension)
, to add new functions to the class. However, is there a way using category extensions to also add new properties to the extension?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,
@interface NSMutableArray (MyStuff)
是一个类别,而不是类扩展。它们在这方面很相似,但实际上确实有很多不同的细节。您无法通过任何一种机制向现有类添加存储。您可以使用关联引用来不过,将数据与实例关联起来。
Note that
@interface NSMutableArray (MyStuff)
is a category and not a class extension. They are similar in this context, but actually do have quite a few different details.You can't add storage to an existing class through either mechanism. You can use Associative References to associate data with an instance, though.
正如您所说,类别只能向类添加方法,而不能向类添加 ivars。您可以在类别中声明
property
和setProperty:
方法,但我不确定您将在哪里存储伪属性的实际数据。As you said, categories can add only methods to a class, not ivars. You could declare
property
andsetProperty:
methods in the category, but I'm not sure where you'd store the actual data of your pseudo-property.