Skip to content

Synthesized ivars are private

Perhaps this isn’t news. Perhaps it doesn’t matter because you’ve provided public accessors. But here are the results anyway.

#import <Foundation/Foundation.h>

@interface A: NSObject
@property (nonatomic, assign) int a;
@end

@interface B: A
- (int)differentGetter;
@end

@interface C: NSObject
@property (nonatomic, retain) A *anA;
- (int)aFromA;
@end

int main(int argc, char *argv[]) {
	@autoreleasepool {
		B *b = [[B alloc] init];
		b.a = 3;
		NSLog(@"[b differentGetter] = %d", [b differentGetter]);
		[b release];
		
		C *c = [[C alloc] init];
		c.anA = [[A alloc] init];
		c.anA.a = 4;
		NSLog(@"[c aFromA] = %d", [c aFromA]);
		[c release];
	}
	return 0;
}

@implementation A
@synthesize a=_a;
@end

@implementation B
- (int)differentGetter { return _a; } // must be at least @protected
@end

@implementation C
@synthesize anA = _anA;
- (int)aFromA { return _anA->_a; } // must be @public
- (void)dealloc { self.anA = nil; [super dealloc]; }
@end

Doesn’t compile:

Untitled.m:37:33: error: instance variable '_a' is private
- (int)differentGetter { return _a; }
                                ^
Untitled.m:42:30: error: instance variable '_a' is private
- (int)aFromA { return _anA->_a; }
                             ^
2 errors generated.