Reputation: 11835
@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.
Upvotes: 1
Views: 154
Reputation: 69027
NSString *tmpString =[[NSString alloc] init];
tmpString
is allocated and initialized
self.orginalString=tmpString;
the string pointed to by tmpString is copied over to self.originalString
(because the property is declared copy
);
[tmpString release];
the string pointed to by tmpString
is released, correctly; nothing happens to the string pointed to by self.orginalString
;
NSString *newString =self.orginalString;
a new pointer is created and initalized to point at the same string pointed to by self.orginalString
; nothing happens to self.orginalString
retain 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 sends release
. Ownership is a local concept to a class, so it is easy to track down.
So, when you do:
NSString *newString =self.orginalString;
newString
is 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:
NSString *newString = [self.orginalString retain];
you are making yourself responsible for releasing the object when you have done with it.
Upvotes: 4
Reputation: 17478
You should visit this link. Actually, we should not check memory leaks with retain count, atleast for NSString.
To check memory leaks, always use Instruments coming with Xcode.
Upvotes: 1