Write only property in Objective-C

Another valid approach is to declare the normal property and make the getter unavailable

@interface MyClass
@property NSString * var;
- (NSString *)var UNAVAILABLE_ATTRIBUTE;
@end

This will raise a compile-time error in case someone tries to access the getter.


The main advantage of this approach is that you actually have a real propertyTM and not a surrogate faked by a instance variable and a setter, which implies that:

  • you’ll get auto-completion when using dot-notation in Xcode
  • all the runtime functions such as class_getProperty and
    class_copyPropertyList will work as expected.

That said, the getter implementation is synthesized anyway and it could be invoked using something like

NSString * string = [myObj performSelector:@selector(var)];

or using NSInvocation (in case of a non-id property)

If you are paranoid and you really want to prevent the client to invoke the getter, you can explicitly throw an exception by providing your own implementation.

@implementation MyClass
- (int)var {
    [NSException raise:NSInternalInconsistencyException
                format:@"property is write-only"];
}
@end

Anyway, if someone seriously wants to tamper with your instance variable, they can use the runtime to access it, so the last precaution is probably useless given the use case. A compile-time error is what you are really looking for.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)