Make an iPhone property read-only in iOS objective-c

时间秒杀一切 提交于 2021-02-08 03:01:14

问题


OK basically I have a class in an iPhone app where I want it to some read only propertys. Meaning that the owning class can read and write the property, but other objects can only read it. I try the "readonly" option when I declare the property, but then my class can't even write it. What use is that?


回答1:


If it's not too inconvenient, just use the ivar or "backing" variable in your class to modify the value. Like this:

In your .h file:

@interface ClassName

@property (readonly,nonatomic) NSInteger readOnlyValue;

@end

In your .m file:

@implementation ClassName

@synthesize readOnlyValue = _readOnlyValue;



_readOnlyValue = 42;

@end



回答2:


Let's assume you wanted to create a property called foo, an int, in your class YourClass.

Do this in your interface (.h) file:

@property(readonly) int foo;

Then in your implementation (.m) file, set up a class extension where you can re-define your property.

@interface YourClass()

@property(readwrite) int foo;

@end

This results in the property being readonly publicly, but readwrite privately.

Then, of course, you synthesize foo in your implementation that follows.

@synthesize foo;



回答3:


While you could go the route of direct iVar access as described in other answers, a better solution is typically to use class extensions. They were designed exactly to solve this problem and, by using them, you can easily refactor your code later to expose the readwrite definition of the @property to other classes in your app without exposing it to all classes.

I wrote up a detailed explanation a while ago.




回答4:


You can implement your own setter in the .m class or synteshize as: foo = _foo; so you can call _foo (private variable) internally




回答5:


On further reflection, the easiest way to achieve this is to add a normal property in a class extension, then declare just the getter in the header. E.g.

Interface:

@interface MyClass: NSObject

- (NSString *)someString;

@end

Implementation:

@interface MyClass ()
@property (nonatomic, retain) NSString *someString;
@end

@implementation MyClass

@synthesize someString;

@end

You'll be able to get and set, using dot notation or otherwise, and directly access the someString instance variable within the class, and everyone that has sight of the interface will be able to get, using dot notation or otherwise.



来源:https://stackoverflow.com/questions/10148619/make-an-iphone-property-read-only-in-ios-objective-c

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