Structure and Interpretation of Computer Programmers

I make it easier and faster for you to write high-quality software.

Tuesday, February 21, 2012

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.
posted by Graham at 09:13  

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress