Reputation: 24771
What is the best way to make an iVar writeable by its owning class, but readonly by other classes?
Is there more than one way?
The only way I can think of is to set a @property (readonly)
for the iVar, but not use dot notation inside the owning class (which I'm guessing wouldn't work with readonly), and in the owning class just reference it directly, without dot notation, then in other class, reference it with dot notation.
But I'm curious if there are other methods.
Upvotes: 1
Views: 333
Reputation: 1441
Use the private specifier for ivars and a class extension to define the accessor - that way the ivar is private to the class.
// FooClass.h @interface FooClass : NSObject { @private int boo;
} @end
// FooClass.m
@interface FooClass () {
}
@property (nonatomic,assign) int boo;
@end
@implementation FooClass
@synthesize boo; // ....
@end
Upvotes: 0
Reputation: 53010
You can make a property read/write just for the implementation. You do this using a class extension, or anonymous category, in your implementation. Easier to demonstrate so, for example, in your .h:
@interface MyClass
@property (readonly) NSInteger age;
...
@end
and in your .m:
@interface MyClass () // class extension/anonymous category for private methods & properties
// implementation of these go in main @implementation
@property (readwrite) NSInteger age;
...
@end
@implementation MyClass
@synthesize age;
...
@end
Now you can use the property within your class read/write and from outside as read-only.
You do the same for private methods.
[Note: This is Objective-C so the above isn't bullet proof - there are ways around it to call the properties setter - but the compiler will flag errors which assign to the property from outside the class.]
After comments:
[Note 2: an anonymous category/class extension is very similar to a named category. The former must be implemented in the main implementation, the latter may be implemented in an @implementation classname (categoryname)
or in the main implementation. Furthermore only the main interface, the interface for a class extension/anonymous category, and the main implementation may declare instance variables; interfaces and implementations for named categories may not. Properties may be declared in both anonymous and named categories, however they may only be synthesized in the main implementation and not in named category implementations. This note is correct at press time, some of these features have changed as Objective-C/Xcode develops.]
Upvotes: 4