Tuesday, March 29, 2011

Use the copy attribute with NSString objects

NSStrings should not be retained instead always be sure to copy them so you have two entirely different NSString objects.

What happens if I retain an NSString?

If we retain an NSString value, it can be modified by some other object and the class containing the NSString object will not know.

eg:- NSMutableString * testString = [NSMutableString stringWithString@"Paul"];
        Student * st = [[Student alloc] init];
        st.name = testString;
       [testString setString:@"Jane"];

In the above example, you can see that we created an immutable string and assigned the name "Paul" to it. Then we set this value to the name property of the Student object. Now what we would want is that the student name should remain "Paul" unless changed explicitly. Now observe the next line of code, since the string object we declared was of type NSMutableString we can change the contents of it.

If the Student.name property is marked as retain, then the value of name will be changed to "Jane" even if it is not set explicitly. Whereas if the Student.name property is marked as assign, then the value of name will remain as "Paul" if someone tries to change the value of testString externally.

So to be on the safe side, always mark your NSString objects with the copy property. If the value assigned to it is mutable, then it will get copied otherwise it will be retained. So we will have no issues either way!

No comments:

Post a Comment