Reputation: 7504
Could anyone please tell me am I handling memory correctly in following code in ARC environment? My concern is how would dict object released if I can't use release/autorelease in ARC! I know if it is strong type then it's get released before creating new one but in following look I don't know how would it works.
NSMutableArray *questions = [[NSMutableArray alloc] init];
for (NSDictionary *q in [delegate questions])
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:[q objectForKey:@"text"] forKey:@"text"];
[dict setValue:nil forKey:@"value"];
[dict setValue:[NSString stringWithFormat:@"%d",tag] forKey:@"tag"];
[questions addObject:dict];
dict = nil;
}
Upvotes: 1
Views: 4124
Reputation: 33428
Yes, you are handling your dict
correctly.
If you have a snippet like the following:
{
id __strong foo = [[NSObject alloc] init];
}
When you leave the scope of the variable obj
, the owning reference will be release. The object is released automatically. But it's not magic stuff involved. ARC will put (under the hood) a call like the following:
{
id __strong foo = [[NSObject alloc] init]; //__strong is the default
objc_release(foo);
}
objc_release(...)
is a sort of release
call but since it bypasess objc messaging it's very performing.
Furthermore, you don't need to set the variable dict
to nil
. ARC will handle this for you. Setting an object to nil
cause a reference to an object to disappears. When an object has no strong references to it, the object is released (no magic involved, the compiler will put the right calls to make it happens). To understand this concept suppose you two objects:
{
id __strong foo1 = [[NSObject alloc] init];
id __strong foo2 = nil;
foo2 = foo1; // foo1 and foo2 have strong reference to that object
foo1 = nil; // a strong reference to that object disappears
foo2 = nil; // a strong reference to that object disappears
// the object is released since no one has a reference to it
}
To have an understanding of how ARC works I really suggest to read Mike Ash blog.
Hope that helps.
Upvotes: 7