[NSMutableDictionary setValue: value forKey: key] save the NSString key?

When adding elements to an NSMutableDictionary using the setValue:forKey: method (I suppose this generalizes to any NSObject ) the dictionary saves the second parameter, NSString ?

For example:

 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; NSString *theString = @"hello"; int i; for (i=0; i<[theString length]; i++){ NSNumber *myInt = [NSNumber numberWithInt:i]; NSString *character = [NSString stringWithFormat:@"%C",[theString characterAtIndex:i]]; [dict setValue: myInt forKey:character]; } [dict release]; [pool release]; 

It is clear that it makes no sense to release myInt in a loop, it is saved by dict , so it cannot be freed until the end of the code. But is the same true for character ? I think that if NSMutableDictionary stores the string in some other way, then you can create a temporary pool around the loop and free these lines instead of waiting until the dictionary is released.

I am also interested to know why retainCount of character is 7fffffff, as if it were NSConstantString , I would expect stringWithFormat return the NSString object that needs to be saved, but it doesn’t seem to be so.

+6
memory-management objective-c
source share
2 answers

Very often, in Cocoa for NSString parameters are copied instead of saved. This is because you could just as easily give the dictionary an instance of NSMutableString . Because the string value may change, NSDictionary creates a copy.

But, no matter how NSMutableDictionary works, you don’t have to worry about having to save character . After you passed it to NSMutableDictionary as a parameter, it is really a problem of this class to decide how to store data, unless the documentation states that your responsibility for saving objects is your responsibility.

I would also not worry too much about retainCount any object. By keeping the number of items too close, you can slide down the rabbit holes that just make you spin the wheels.

Finally, I really don't think you need to create your own autorun. If you do not know with absolute certainty that theString will be very long, or you have already seen high memory usage in tools, adding an autocomplete pool is an unnecessary optimization.

+8
source share

You do not need to save the character there, the dictionary saves it when you set it as a key, and your own code does not need to save it.

You also don't have to worry about why the number of deductions is not as expected. The Foundation may have some Flyweight-like instances of loading single-character NSString instances. In any case, if you have the correct memory management in accordance with the recommendations, you will be fine, regardless of what the framework does behind the scenes. http://iamleeg.blogspot.com/2008/12/cocoa-memory-management.html

+4
source share

All Articles