Reputation: 1559
Lets suppose I created a property tempStr that is of NSString type. I synthesized it obviously.
In one of my methods, I set the value of tempstr to be yellowcolor. Then just after that I reinitialized tempStr with redcolor.
So I wanna know what happens to the memory of tempStr in this case.
Thanx.
Upvotes: 1
Views: 150
Reputation: 2312
It depends on what attribute you set for your property: retain
, assign
or copy
.
@property (retain) NSString *tempStr
: the old value (yellowcolor) would be released and the new value (redcolor) would be retained. The only exception is when yellowcolor == redcolor
. Then nothing would happen, because old and new values are the same.@property (assign) NSString *tempStr
: there would be no release/retain operations. It is equal to changing just a pointer. So after this operations yellowcolor won't be released and you'll lost a reference to it (if there is no other reference to it in your code). So it can cause a memory leak.@property (copy) NSString *tempStr
: it's similar to retain
but it call copy
on new value instead of just retain
, so it'd create a duplicate object in a memory. Considering NSString, it's equal to retain
, because NSString is immutable, so there is no need to make a duplicate.You can find some code examples here.
EDIT: As @Bavarious mentioned, copy
is equal to retain
only if you initialize this property with NSString
. It won't be equal if you initialize it with NSMutableString
, because this one is mutable, so the "proper" copy would be make.
Upvotes: 2
Reputation: 11834
A synthesized setter looks a bit like this:
- (void)setSomeString:(NSString *)newString
{
if ([newString isEqualToString:someString]) return;
[someString autorelease];
someString = [newString copy]; // or [newString retain], depends how you defined the property ...
}
So the old value is released when the new value is assigned to the pointer.
Upvotes: 1