开发者

Do I have to remove each element of dictionary when I remove array?

When I remove array, do I have remove e开发者_JAVA技巧ach element of dictionary also?

NSMutableArray *myArry = [NSMutableArray arrayWithCapacity:100];
NSMutableDictionary *myDic = [NSMutableDictionary dictionaryWithCapacity:10];
[myArray addObject:myDic]; // this is done in loop


[myDic removeAllObjects]; // Is this necessary?
[myArray removeAllObjects];


No. When you release an array, every item inside is automatically send a release message so you are not required to remove them, release them or adjust them other that simply releasing the array using -[NSArray release]

The correct code is

NSMutableArray *myArry = [[NSMutableArray alloc] initWithCapacity:100];
NSMutableDictionary *myDic = [NSMutableDictionary dictionaryWithCapacity:10];
[myArray addObject:myDic]; // this is done in loop
…
[myArray release]; // To dispose of the array and it's contents. No need to remove objects

A NSDictionary behaves in the same way, that is, you do not need to remove them, only release them. In the move example, the dictionaries you are adding are autoreleased meaning that once myArray releases them, they will be dealloc'd


Ok, when you release a dictionary or you remove objects from an object that owns it and its retain count is 0, it means it is released. If the dictionary was only owned by the array(it had a retain count of one) and you removed the object, the array doesn't own the dictionary so it would release it. This would subsequently release the objects inside the dictionary.

Its better to read up on memory management and object ownership before programming because you dont want leaks. http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html


You don't need to make either of those calls to removeAllObjects with your code as is (for memory management's sake, anyway), because both the NSMutableArray and the NSMutableDictionary are autoreleased (since you used the class method initializers).

However, for the sake of not flooding the autorelease pool local to this bit of code (and depending on how many iterations your loop to add dictionaries to the array is going through), you might find some increased memory efficiency using the following code:

NSMutableArray *myArry = [[NSMutableArray alloc] initWithCapacity:100];
NSMutableDictionary *myDic = [[NSMutableDictionary alloc] initWithCapacity:10];
[myArray addObject:myDic]; // this is done in loop
[myDic release];
// ... other code...
[myArray release];

If you'd like to re-use the array without reallocating it at this point, you can also use removeAllObjects to release all of its contents, thus releasing the contents of the dictionaries therein as well--as long as you still send it a release message when you're done using it, and before you leave scope.


just use "release". If you are using malloc than "free".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜