@property (nonatomic,copy) NSString *orginalString;
..
NSString *tmpString =[[NSString alloc] init];
self.orginalString=tmpString;
[tmpString release];
NSString *newString =self.orginalString;
What happens here to newString?, is this correct what I am doing?
orginalString retain count 1 at first, and when it is referenced with another pointer “newString” its retain count will be 2? do I need to say “self.orginalString=nil” in the end? there are serious memory leaks but dont know it is something related with this.
tmpStringis allocated and initializedthe string pointed to by tmpString is copied over to
self.originalString(because the property is declaredcopy);the string pointed to by
tmpStringis released, correctly; nothing happens to the string pointed to byself.orginalString;a new pointer is created and initalized to point at the same string pointed to by
self.orginalString; nothing happens toself.orginalStringretain count; it’s just a second pointer pointing to the same object;at this point, if you don’t release somewhere
self.orginalString, it will be leaked.When you are dealing with memory management in OBjective C, my suggestion is not try and reason in terms of “retain count”; retain count is just the mechanism that is used by the ObjC runtime to keep track of objects; it is too low-level and there are too many other objects around to increase or decrease the retain count, so that you immediately loose count.
The best way, IMO, is reasoning in terms of ownership: when an object wants ownership of another, it will send a
retain; when it has done with it, it sendsrelease. Ownership is a local concept to a class, so it is easy to track down.So, when you do:
newStringis just a pointer to a not-owned object; you do not need to balance that assignment with a release; on the contrary, if you do:you are making yourself responsible for releasing the object when you have done with it.