0

I've got the following object:

@interface Foo : NSObject
@property (readonly, strong) NSString *someVar;
@end

@implemtation Foo
@sythensize someVar = _someVar;
@end

And then I subclass it:

@interface Bar : Foo
-(id)initWithString:(NSString *)string;
@end

@implementation Bar
-(id)initWithString:(NSString *)string {
  _someVar = string;
}
@end

but I get a "use of undeclared identifier _someVar"..... Why doesn't Bar know about foo's instance variable _someVar ?

patrick
  • 9,290
  • 13
  • 61
  • 112
  • possible duplicate of [Synthesized property of a protocol not seeing superclass' ivar](http://stackoverflow.com/questions/2963417/synthesized-property-of-a-protocol-not-seeing-superclass-ivar), [Subclass of class with synthesized property cannot access ivar](http://stackoverflow.com/questions/10943042/) – jscs Sep 09 '12 at 18:51
  • closely related: [What is the visibility of sythesized ivars?](http://stackoverflow.com/questions/8510464/), [Direct access to synthesized ivars in subclass](http://stackoverflow.com/questions/12234063/) – jscs Sep 09 '12 at 18:53

1 Answers1

1

Always use getters/setters. Low level/direct access is only appropriate when seeking billionth of a second performance improvements, and in that case I question whether you should ditch Obj-C altogether and switch to just C.

Here is how I do it:

@synthesize someVar;

-(id)initWithString:(NSString *)string {
  self.someVar = string;
}

Or, if I have a good reason not to use accessor methods, the. I don't use @synthesize at all.

Also, in the latest version of Xcode you can skip the @synthesize line.

Abhi Beckert
  • 32,787
  • 12
  • 83
  • 110
  • It's not "not safe", it's _not possible_. The compiler won't let you do it. That's the point of the question. – jscs Sep 09 '12 at 19:02
  • By "not safe" I meant you shouldn't use that practice in any common code situation, even ones where it will work. I've updated my answer to explain it clearer. – Abhi Beckert Sep 09 '12 at 19:08
  • I see.. My pattern has usually been to have readonly properties that I know aren't going to ever change, and just directly set their instance variable upon initialization of the instance, that way I wouldn't ever have to worry about some other object changing the value of one of these properties..... – patrick Sep 09 '12 at 19:19
  • Then declare it readonly in your public `@interface` and have a second private `@interface` declaring it as read/write. Normally the second interface is "nameless" and in the same file as the `@implementation`: http://stackoverflow.com/a/4586556/19851 Not sure about writing to these from a subclass, maybe update your question to ask that? – Abhi Beckert Sep 09 '12 at 19:31