Murdock
Murdock

Reputation: 866

"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) populateFetchDataDict {

    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:

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

Upvotes: 0

Views: 79

Answers (1)

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];
    }

}

Upvotes: 1

Related Questions