Lazy initialization does not work iPhone

Thus, I have many user objects that can contain a lot of data or very little data depending on user input. I obviously do not want to create storage for a lot of data, if only a little is required. So I heard about initialization, and it sounds 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 name myObject in its initializer, then this works fine. However, when I try to do this lazy initialization, the name of the object becomes nil after trying to set it. What am I doing wrong?

+4
source share
1 answer
 @property (strong) NSString *name; @synthesize name = _name; - (NSString *)name { if (!_name) { _name = [[NSString alloc] init]; ... } return _name; } 
+3
source

All Articles