allocing object when assigning
I am really new to objc and I am trying to understand as much as possible and get a good routine when it comes to mem management.
My question is if code like this is dangerous (i love short code)
NSMutableArray *items = [[NSMutableArray alloc] init];
[items addObject:[[UIBarButtonItem alloc]
initWithTitle:@"Login"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(tryUserInput)]];
[self.toolbar setItems:items animated:TRUE];
[self.view addSubview:self.toolbar];
[items release];
In the examples I can find people always create the object that they add in the array, add it and then release it. If I alloc it and adds it at the same time, the array will take care of it aye? And I am releasing that when I'm done with it. Also, can I write it like this?
self.开发者_如何学JAVAnavigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Logout" style:UIBarButtonItemStyleDone target:nil action:nil];
Or should I attach an autorelease on that one?
If I understood it correclty, since the "navigationitem" is a property it retains the object and takes care of it. And the array retains all the objects I add to it. So everything should be fine?
Thanks for your help
You need an to send an autorelease
to the UIBarButton, or you'll have a leak.
When you alloc
it, it has a "retain count" of +1; when you add it to the array it goes to +2. You need it to go back to +1, so that the only owner will be the array, and the UIBarButton will be deallocated when the array is freed. You can do it in two ways:
[items addObject:[[[UIBarButtonItem alloc]
initWithTitle:@"Login"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(tryUserInput)] autorelease]];
or
UIBarButtonItem *item = [[UIBarButtonItem alloc]
initWithTitle:@"Login"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(tryUserInput)];
[items addObject:item];
[item release];
精彩评论