初始化只读属性 [英] Initializing a readonly property

查看:115
本文介绍了初始化只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个只读属性.我想使用创建该类实例的类中的值进行初始化,例如

I was trying to create a property which is readonly. I wanted to initialize with a value from the class creating an instance of this class, e.g.

@property (retain,readonly) NSString *firstName;

我试图这样初始化它:

-(id)initWithName:(NSString *)n{ self.firstName = n; }

-(id)initWithName:(NSString *)n{ self.firstName = n; }

一旦执行此操作,编译器将报告一个错误,指出无法分配readonly属性.那我该怎么办呢?

Once I did this, the compiler reported an error that the readonly property cannot be assigned. So how can i do this ?

推荐答案

直接分配给实例变量(如果需要,请不要忘记添加retaincopy)或在私有类扩展.像这样:

Either assign to the instance variable directly (don't forget to add a retain or copy if you need it) or redeclare the property in a private class extension. Like this:

在您的.h文件中:

@property (readonly, copy) NSString *firstName;

在您的.m文件中:

@interface MyClass ()

// Redeclare property as readwrite
@property (readwrite, copy) NSString *firstName;

@end


@implementation MyClass

@synthesize firstName;
...

现在,您可以在实现中使用合成的setter,但类接口仍将属性显示为只读.请注意,其他导入.h文件的类仍可以调用-[MyClass setFirstName:],但是他们不知道它存在,并且会收到编译器警告.

Now you can use the synthesized setter in your implementation but the class interface still shows the property as readonly. Note that other classes that import your .h file can still call -[MyClass setFirstName:] but they won't know that it exists and will get a compiler warning.

这篇关于初始化只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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