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;

@interface B: A
- (int)differentGetter;

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

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;

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

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

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.

About Graham

I make it faster and easier for you to create high-quality code.
This entry was posted in Uncategorized. Bookmark the permalink.