开发者

"Release>nil>init" An acceptable way to update an NSMutableDictionary?

Is the method below an acceptable (i.e. best-practices, non-hacky) way of updating an NSMutableDictionary?

Basically I want the method to check if the dictionary has been initialized/populated yet. If it has NOT then I want it to go ahead and populate it with a certain set of iVars I have, with the matching set of keys.

If it HAS already been initialized/populated though, I want a refresh, and I wanted to avoid having to write out setObject:forKey: for every single element in the dict.

So...

  1. Is "Release">"Set nil">"Re-init" an acceptable approach to refreshing this dictionary?
  2. If so, is that the only way to do it for a dictionary of large values unless I want to repeat line after line of setObject:forKey:

Thanks! Code follows:

- (void) popula开发者_开发问答teFetchDataDict {

    if (!self.fetchDataDict) {
        self.fetchDataDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:object1, @"key1", object2, @"key2", object3, @"key3", object4, @"key4", nil];
    } else {
        [fetchDataDict release];
        fetchDataDict = nil;
        self.fetchDataDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:object1, @"key1", object2, @"key2", object3, @"key3", object4, @"key4", nil];
    }

}

Minor notes:

  • fetchDataDict is an iVar, as are all of the objects, so assume the object1, object2, etc. would actually be self.object1, self.object2...
  • Also, I accessed the fetchDataDict iVar directly for release and nil, as I thought that's what we're supposed to do, but please correct me if I'm wrong.

This question is learning-focused, so long explanations are welcome!


Since you are using property accessors, and I am assuming you have the properties marked as retain, you can simply set the new value - the old will be released automatically. In fact the only reason your code doesn't crash right now is because you are over-retaining the new dictionaries by not autoreleasing them, which you should do.

In fact your code can simply look like:

- (void) populateFetchDataDict {
        self.fetchDataDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:object1, @"key1", object2, @"key2", object3, @"key3", object4, @"key4", nil];
}

If you only wanted to set those specific values in an existing dictionary, then you could add back in the if statement and merge in those default values with the existing dictionary:

- (void) populateFetchDataDict {

        NSDictionary *defaultDict = [NSMutableDictionary dictonaryWithObjectsAndKeys:object1, @"key1", object2, @"key2", object3, @"key3", object4, @"key4", nil];
    if (!self.fetchDataDict) {
        self.fetchDataDict = defaultDict;
    } else {
        [self.fetchDataDict addEntriesFromDictionary:defaultDict];
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜