Quote:
Originally Posted by longst
a great tutorial for new comers, especial for someone like me coming from C# and Java.
I am still not sure I did quite understand with this part
"
The same would be true if a new value gets assigned to the property. Remember, the setter will release (-1) the old value, and the object we created is now the old value. So again we are left with a +1 net retain count, again we do not have any means to communicate with the object, and again it is a leak. And as a double-bonus, if the new object is another alloc/init creation, we're replacing a leaked object with another leaked object.
"
Could you please show me a sample code regarding this part Thank you
|
"For every "alloc or retain" you should have a "release" and vice-versa."
So just using ivars:
someView = [[UIView alloc] init]; // Alloc message sent.
Using accessors:
self.someView = [[UIView alloc] init]; // Alloc and retain message sent.
So if your project was setup up with:
.h
@property (nonatomic, retain) UIView *someView; //telling accessors to include a retain message using the retain attribute.
.m
@synthesize someView;
Step 1: allocates space for the object and initializes it, then "do stuff with object", then releases it.
someView = [[UIView alloc] init];
"Do stuff with object"
[someView release];
someView was released from the allocated space. But now the ivar points to an empty space that once contained your object because you did not nil out the ivar using someView = nil;
Step 2: accessor which will call a release on the old value in Step 1: and retain the new value we see here
self.someView = [[UIView alloc] init]; // Alloc & Retain *Needs 2 releases sometime in the future
but since the old value in step 1 has already used a release for its alloc, it has long already left the place someView is currently still pointing to.
It will crash because it tries to release something not there!
Remember: someView is different than self.someView
FUN ANALOGY
The cookie monsta tells you to stick your hand out and then put a cookie in it (alloc),
you take a bite(do stuff),
then the cookie monsta takes it away from you because he is the cookie monsta and he does what he wants,
"I DO WHAT I WANT!!!"(release sucka!)
OM NOM NOM!
You don't have a cookie anymore and feel sad and hungry....awwwww.
COOKIE MONSTA DON'T CARE!!!
Cookie monsta come back still looking for the cookie in your hand...Again...
(release sucka!)
...but you don't have anything to give the cookie monsta...
COOKIE MONSTA DON'T CARE!!!
He rears up, opens his mouth, and BITES YOUR ARM OFF! OM NOM NOM NOM!
THE END
- It's a harsh life. lol