Dev Singh
Dev Singh

Reputation: 65

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

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?

Upvotes: 2

Views: 1856

Answers (5)

Jay Slupesky
Jay Slupesky

Reputation: 1913

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

Upvotes: 3

Tommy
Tommy

Reputation: 100602

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.

Upvotes: 0

Extra Savoir-Faire
Extra Savoir-Faire

Reputation: 6036

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;

Upvotes: 7

bbum
bbum

Reputation: 162712

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.

Upvotes: 2

Justin
Justin

Reputation: 2999

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

Upvotes: 0

Related Questions