Search code examples
iphoneobjective-ccocoacopyretain

Question about retain and copy in Objective c


This question confused me a little. In the ".h" file.

@property (nonatomic,retain) NSMutableString *str1;
@property (nonatomic,copy) NSMutableString *str2;

In the ".m" file.

NSMutableString *testRetain = [[NSMutableString alloc] initWithString:@"prefix"];
 NSLog(@"retain count is %d",[testRetain retainCount]);
 NSLog(@"mem add is %p",testRetain);

 str1 = testRetain;
 NSLog(@"retain count is %d",[testRetain retainCount]); 
 NSLog(@"mem add is %p",testRetain);

 str2 = testRetain;
 NSLog(@"retain count is %d",[str2 retainCount]); 
 NSLog(@"mem add is %p",str2);

all the retainCount and memory address are same. As I know, @property (nonatomic,retain) will add the retainCount of the object which be pointed.So the second part of code should output the same memory address and the different containCount from first part of code. and @property (nonatomic,copy) will copy the object to a new area.So the third part of code should output the different memory address from first part of code. Why i got this result. Thanks a lot.


Solution

  • Two points. First, and most important: don't use retainCount as a debugging tool. There are many reasons why it might not give you the value you're expecting. It says as much in the documentation.

    But in this case -- point two -- the reason it's not working is that you're accessing the variables directly rather than using the accessors.

    Instead of:

    str = testRetain;
    

    Try:

    self.str = testRetain;