Reputation: 5667
I have gone through objective-C literals & class methods, but I am not clear from Memory point of View. I am confused to use which version of the code. I have two piece of code & I would like to understand the difference between them from Memory Leak point of View.
Assuming that "returnArray" is Array to be returned
Version 1
if([tempArray count] > 0) {
for(NSDictionary *dict in tempArray) {
NSDictionary *tempDict = [
[NSDictionary alloc]initWithObjectsAndKeys:
[dict objectForKey:@"verifiedEmail"],@"verifiedEmail",
[dict objectForKey:@"identifier"], @"identifier",
nil
];
[returnArray addObject:tempDict];
}
}
Version2
if([tempArray count] > 0) {
for(NSDictionary *dict in tempArray) {
NSDictionary *tempDict = @{
@"verifiedEmail" : [dict objectForKey:@"verifiedEmail"],
@"identifier" : [dict objectForKey:@"identifier"],
};
[returnArray addObject:tempDict];
}
}
Upvotes: 0
Views: 105
Reputation: 42977
In manual memory management when you alloc
an object such as [NSDictionary alloc]initWithObjectsAndKeys:
you are getting a retained object. means you are responsible to release that object. Where as [NSDictionary dictionaryWithObjectsAndKeys]
giving you a autoreleased object. Your second version of code is modern objective c style creating dictionary same as [NSDictionary dictionaryWithObjectsAndKeys]
(in particular replacement for +[NSDictionary dictionaryWithObjects:forKeys:count:]) . In memory concern second one is autoreleased. If you are not sure about memory management use ARC
Upvotes: 0
Reputation: 91
You will leak memory using Version 1. You're allocating an NSDictionary but then overwriting its pointer (the local tempDict) so have no way to release it. Version 2 will not leak memory since the creation of the NSDictionary object creates an auto-released object. (All of this assumes you are using Manual Retain/Release, rather than ARC.)
Upvotes: 0
Reputation: 26385
Supposing that you are NOT using ARC:
Upvotes: 2
Reputation: 2351
Version 1 is creating a dictionary everytime and version two is giving out an autoreleased version of dictionary.
Version 2 is equivalent to [NSDictionary dictionaryWithObjectsAndKeys]
method.
Upvotes: 0