在iOS类扩展中定义属性 [英] Defining a property in iOS class extension

查看:410
本文介绍了在iOS类扩展中定义属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在类扩展中向UITableView添加一个属性:

I would like to add a property to UITableView in a Class Extension:

@interface UITableViewController ()

@property NSString *entityString;

@end

然后导入扩展名,然后在UITableViewController的子类中使用entityString属性:

Then I import the extension and then I use entityString property in a subclass of UITableViewController:

@implementation CustomerTableViewController

- (void)viewDidLoad {
    self.entityString = @"Customer";
    ...
    [super viewDidLoad];
}
...

编译器将自动合成相关的访问器 主要类中的方法(...) 实施.

the compiler will automatically synthesize the relevant accessor methods (...) inside the primary class implementation.

但是当我尝试执行它时,出现此错误:

But when I try to execute it I get this error:

-[CustomerTableViewController setEntityString:]:无法识别的选择器已发送到实例0x737b670

-[CustomerTableViewController setEntityString:]: unrecognized selector sent to instance 0x737b670

我做错了什么?也许子类无法访问该属性?

What am I doing wrong? maybe the property cannot be accessed by subclasses?

推荐答案

类扩展用于声明其他接口(方法和属性),其实现合同将在类的主对象内得到满足@implementaiton.

A class extension is used to declare additional interface -- methods and properties -- whose implementation contract will be met within the class's primary @implementaiton.

这正是为什么您不能通过类扩展添加存储-添加ivars的原因.类扩展是一个接口,不多也不少. @synthesize是为@property声明创建存储的原因,但是@property@synthesize只能出现在该类的@implementation中(无论是显式还是编译器的默认行为).

Which is exactly why you can't add storage -- add ivars -- via a class extension. A class extension is an interface, no more, no less. @synthesize is what creates storage for @property declarations, but @synthesize of an @property can only appear in the @implementation of the class (whether explicitly or as a default behavior of the compiler).

由于无法重新编译框架类,因此无法向其添加ivars.

Since you can't recompile the framework class, you can't add ivars to it.

@prashat的答案是将存储添加到现有类的一种方法.但是,走那条路线通常是不可取的.将状态挂在框架类之外willy-nilly表示设计不良,并且随着时间的推移,将使您的应用程序变得更加难以维护.

@prashat's answer is one way to add storage to an existing class. However, going that route is generally undesirable; hanging state off of framework classes willy-nilly is a sign of poor design and will make your application significantly more difficult to maintain over time.

最好重新审视设计,了解为什么当前需要将状态附加到不能直接包含状态的对象,然后将其重构.

Far better to revisit your design, understand why you currently require attaching state to an object that can't directly contain it, and refactoring that requirement away.

这篇关于在iOS类扩展中定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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