Reputation: 5630
So I have a lot of custom objects that could contain a lot of data, or very little data depending on the user's input. I obviously don't want to to create storage for a lot of data if only a little is needed. So I heard about initialization and it sounds like exactly what I want; I just can't get it to work. Here is an example of one of my attempts:
@synthesize name;
...
- (NSString *)name {
if (!name) name = [[NSString alloc] init];
return name;
}
and then somewhere else
myObject.name = localName;
If I alloc
and init
myObject's name in its initializer then this works fine. However, when I try the above lazy initialization, the object's name becomes nil
after trying to set it. What am I doing wrong?
Upvotes: 4
Views: 882
Reputation: 33101
@property (strong) NSString *name;
@synthesize name = _name;
- (NSString *)name {
if (!_name) {
_name = [[NSString alloc] init];
...
}
return _name;
}
Upvotes: 3