Objective-C Equivalent of Public Get/Protected Set Property in C#

c++objective-cproperties

Is there any way to create a property like this C# property in Objective-C?

public int prop { get; protected set;}

Essentially, I want to make it possible to get the value from outside the class, but to only be able to set the value from within the class.

Best Answer

The easiest way to accomplish this is to declare the property as readonly in the public interface for MyClass (i.e. the .h file):

@property (readonly) NSInteger prop;

Then, in .m file for that class, declare a class extension (a category with an empty name). In class extensions, you may redeclare a @property to change its writeability to readwrite:

@interface MyClass ()
@property (readwrite) NSInteger prop;
@end

@implementation MyClass
@synthesize prop;
...
@end

Of course, Objective-C does not enforce access restrictions, so there's nothing stopping some rogue code from calling -[MyClass setProp:]. The compiler will flag this as a warning, however, which is as good as you can get in Objective-C. Unfortunately, there is no standard way to document this "protected" writeable property to subclasses; you'll have to settle on a convention for your team and or put it in the public documentation for the class if it's in a framework that you're going to release.