I have been using ojective c for almost a week, and I am mainly a c++ coder. After I read Apple's memory management guide, I try to bring my memory usage style in c++ into objective c... I tried to conclude these scenarios, I think I won't make memory mistake if I follow these instructions. Please kindly let me know if I am wrong :)
I will try not to use autorelease, personally speaking, by using autorelease, there might always be some redundent memory before certain auto release pool is drained. I will only use release, which make sure my application uses minimum memory at any time.
Another thing Apple says, which I describe with my own words, is: everytime I add an retain/alloc/copy, I should add a release somewhere.
Here are all the scenarios I conclude:
In the same function: alloc an object, use it, and release it
In the init function of a class, alloc an object, in the dealloc function of the class, release the object
When it's necessary to own a pointer, one should retain an input pointer in a method of a class(let's say method A), and then release the pointer in the dealloc function of the class.
I found that the timing of using retain in objective c is the same to the timing of using memcpy in c/c++, so I take retain as a "memory efficient copy"
If the input retained pointer is to set to a member pointer variable, then one should release the member pointer first. So in case[3], alloc in init of the class is paired with release in method A, and the retain in method A is paired with the release in dealloc
Return a pointer as return value. Honestly speaking I never do such things when I use c++. It's OK if to return a member pointer, coz someone will take care of it:
-(UIButton*) getTheButton() { return theButton; }
But it's really terrible to return a pointer to a locally allocated object:
-(UIButton*) getTheButton() { UIButton* myButton = [[UIButton alloc] init]; return myButton; //TERRIBLE! }
Someone might say I should use autorelease in that case, but I simply want to bypass that solution by using this: I will only return member pointers, or I will not return pointers, I will only operate on given input pointers.
-void operateOnTheButton(UIButton* button) { [button release]; button = [[UIButton alloc] init]; }
So, please kindly let me know if there is any problem if I follow the memory usage instructions above.
Thanks :D
button
is an in-out parameter. That is not the case, in-out would be(UIButton**)button
. – Georg Fritzsche