简体   繁体   中英

How to implement a custom copy property with ARC on iOS

I'm trying to implement a custom property with automatic reference counting on iOS.

My .h file:

@interface AObject : NSObject
@property(nonatomic,copy) NSString* str;
@end

My .m file:

@implementation AObject

@synthesize str = _str;

-(void)setStr:(NSString *)str {
    if (![_str isEqualToString:str]) {
       // Which one is right?
        _str = [str copy];   //(1)
        _str = str;          //(2)
    }
}

@end

Which of the two lines (1) and (2) should I use? I tested both, and both seemed to work. Is there a difference?

ARC would only automatically do retaining, not copying. If you would like it to be copied, so (1) is the correct one.

_str = [str copy]; is correct. The reason to copy instead of retain (ARC is impliciting retaining the object for you) is because NSMutableString is a subclass of NSString . This means that str could be an NSMutableString and could later change its' value which is probably not what you want. There's no performance implications for using copy because if str is a non-mutable NSString then copy will not create another copy, it will simply increase the retain count.

What Benedict says in specific answer to your question is correct (+1), but you have another minor "issue".

if (![_str isEqualToString:str])

is overkill. You might as well do

if (_str != str)

which is a much faster comparison and only leads to a significant penalty if str is a mutable string that compares equal to _str .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM