Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error accessing generated ivars when I override setters and getters in Modern Objective-C

Tags:

I know now the new Objective-C compiler lets you not need to synthesize your properties anymore. I have one file that has two classes in it. My .h for a simple helper class looks like this:

@interface ViewFrameModel : NSObject

@property (nonatomic, strong) UIView *view;
@property (nonatomic, assign) CGRect frame;

- (id)initWithView:(UIView *)view frame:(CGRect)frame;

@end

In the same .h file, for my other class (class 2), I have:

@property (nonatomic, strong) ViewFrameModel *viewFrameModel;

In class 2.m, I can do this:

- (void)setViewFrameModel:(ViewFrameModel *)viewFrameModel {
    _viewFrameModel = viewFrameModel;        
    [self pushViewFrameModel:viewFrameModel];
}

This works fine with no complaints from the compiler, however, when I add this:

- (ViewFrameModel *)viewFrameModel {
    return _viewFrameModel;
}

I get two complaints, one on the first method setViewFrameModel:

"Use of undeclared identifier _viewFrameModel, did you mean viewFrameModel"

And the other on return _viewFrameModel:

"Use of undeclared identifier _viewFrameModel, did you mean viewFrameModel" "Reference to local variable viewFrameModel' declared in enclosing context"

Why do I get these errors when I add in the

- (ViewFrameModel *)viewFrameModel {
    return _viewFrameModel;
}

method? I want to override this method with some custom info, but it's complaining at me :-. Thoughts? TIA.

like image 643
Crystal Avatar asked Jan 08 '13 20:01

Crystal


2 Answers

If you override both the setter and the getter, the compiler will not automatically create the instance variable for you anymore. You can add it to your class implementation like so:

@implementation ClassName {
    ViewFrameModel *_viewFrameModel;
}
...
@end
like image 58
Carl Veazey Avatar answered Oct 02 '22 16:10

Carl Veazey


Here is the results of some testing I did last year: iOS automatic @synthesize without creating an ivar.

In short, you need to use @synthesize or declare an iVar explicitly.

like image 32
Jeffery Thomas Avatar answered Oct 02 '22 17:10

Jeffery Thomas