Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lazy initialization in iOS

Data comes from the server in JSON, which is placed in a NSDictionary. Depending on type of requested data the new class object will be created from this NSDictionary. There're a lot of data comes, so the object holds a reference to NSDictionary and extracts a value only when referring to a particular variable. Something like lazy initialization:

- (NSString *)imgURL {
    if (_imgURL == nil) {
        _imgURL = [self makeObjForKey:kImageURL];
    }
    return _imgURL;
}

This significantly increases application speed, but produces other problems:

  1. If a value is absent in NSDictionary, it remains nil. Then for each subsequent call to this variable there occurs search for it in NSDictionary.
  2. When copying the entire instance of the class (NSCopying protocol), all variables are copied, producing convertion from entire NSDictionary.

Solutions:

  1. Put some flag indicating that value has been checked. But then you have to add additional checks
  2. Only copy NSDictionary for object instance, but then later have to parse same variables again

Anyway these solutions are not optimal. Maybe somebody faced with a similar problem and can advise other techniques.

like image 403
Lion Avatar asked Oct 20 '22 16:10

Lion


1 Answers

NSDictionary lookups are very fast. Unless this is a truly enormous dictionary, I wouldn't worry too much about the lookup. If you have some properties that are checked particularly often, then you could optimize them with a special flag, but I usually wouldn't worry about it.

For copying, my first recommendation is to make this object a value (immutable) object. Initialize it once with JSON and then provide no mutators (that may be what you're doing already). Then copy is trivial; just return self. You don't need to make a real copy, because all copies are interchangeable. One of the great benefits of value objects is how cheap and easy they are to copy.

If you sometimes really need a mutable version, then follow the NSArray/NSMutableArray pattern. Then only the mutable version will have to deal with copies (in which case you should just copy the dictionary; not the cached objects).

like image 166
Rob Napier Avatar answered Oct 24 '22 00:10

Rob Napier