I have been working with Objective-C for a month approximately but regretfully I’m still a complete dummy in memory management so I need your advice. I pass an array from one file to the other like this
BidView *bidView = [[[BidView alloc] init] autorelease];
NSLog(@"%i",[bidView.seatsForTableCreated retainCount]);
bidView.seatsForTableCreated = [NSArray arrayWithArray:seats];
NSLog(@"%i",[bidView.seatsForTableCreated retainCount]);
[self.navigationController pushViewController:bidView animated:YES]; `
NSLog tells me that retain count of seatsForTableCreated has raised from zero to two. Then, when I quit the BidView screen (without doing anything with seatsForTableCreated array) I’ m doing the following:
NSLog(@"%i",[seatsForTableCreated retainCount]);
[seatsForTableCreated release];
NSLog(@"%i",[seatsForTableCreated retainCount]);
it’s quite unclear for me. Now NSLog tells me (both times) that retain count is 1. Then I repeat this procedure (running the same application I mean) and each time things are the same:0-2-1-1. So my questions are:
1)Why 0 to 2? Why retain count increases to 2 not to 1?
2)why then it drops to 1 without being impacted in any way?
3)Why it still remains 1 after i’ve released it?
4)How would you manage the memory in such a case?
Great thanks in advance
My advice assumes you are using Xcode 4+ and you are not using ARC,
command+shift+B will analyse your memory management (and dead stores and such). I think you got it right. Don’t worry about the retain counts so much until you get a complaint from Analyze or find leaks with Instruments. I am not sure how reliable retain counts are. I have seen comments on SO saying not to rely on them.
You are following the rules well
New, Alloc, Copy, Retain –> You will need to release this object when you are done with it.
I am also assuming in BidView.h your property is declared as
@property(nonatomic, retain) NSArray * seatsForTableCreated;
So releasing that in the dealloc method in BidView.m is good memory management
EDIT
It works when even though you don’t allocate seats for table created because.
self.seatsForTableCreated = ...will retain whatever object you are setting there.So if you have a property with (retain) in the declaration, you can consider
as setting property and retaining it. The properties were added to objective-C to reduce similar code being in every class.
A property in .h
Compiler will create 2 methods for you automatically when you
@synthesizein the .m// Note, the compiler may not create the exact same code as above when creating the //setProperty method. If it does, it could be subject to change.
I tried to figure out why Analyze isn’t catching the issue when you don’t release your property, but haven’t. That is confusing and I want to explore it further.