NSString property: copy or retain?

前端 未结 10 1156
予麋鹿
予麋鹿 2020-11-22 02:53

Let\'s say I have a class called SomeClass with a string property name:

@interface SomeClass : NSObject
{
    NSString* name;
}

@p         


        
10条回答
  •  日久生厌
    2020-11-22 02:57

    You should use copy all the time to declare NSString property

    @property (nonatomic, copy) NSString* name;
    

    You should read these for more information on whether it returns immutable string (in case mutable string was passed) or returns a retained string (in case immutable string was passed)

    NSCopying Protocol Reference

    Implement NSCopying by retaining the original instead of creating a new copy when the class and its contents are immutable

    Value Objects

    So, for our immutable version, we can just do this:

    - (id)copyWithZone:(NSZone *)zone
    {
        return self;
    }
    

提交回复
热议问题