我理解如果一个object属性有一个可变子类,那么一个属性应该是copy
而不是strong
,以防止该变量在没有该类权限的情况下发生变异。我使用strong
创建了两个不同的例子,只是为了完全理解原理,但我不理解第二个例子的结果。
@interface Person: NSObject
@property (nonatomic, strong) NSArray* siblings;
@end
@implementation Person
//init - initialize empty siblings array
//setter
- (void)setSiblings:(NSArray *)siblings{
_siblings = siblings;
}
@end
示例1:
int main{
NSMutableArray* siblings = [@[@"Nikita"] mutableCopy];
Person* person = [Person alloc] init];
//This calls the setter and creates a strong
//reference to the siblings array above
person.siblings = siblings;
NSLog(@"1: %@ ", person.siblings);
//Here I am able to change the siblings array and that
//change will reflect inside the person.siblings instance variable
[siblings addObject:@"Andre"];
NSLog(@"2: %@ ", person.siblings);
}
Output:
1: (Nikita)
2: (Nikita, Andre)
示例2:
int main{
NSMutableArray* siblings = [@[@"Nikita"] mutableCopy];
Person* person = [Person alloc] init];
//This calls the setter and creates a strong
//reference to the siblings array above
person.siblings = siblings;
NSLog(@"1: %@ ", person.siblings);
//Here the change is not reflected in person.siblings instance variable
siblings = [@[@"Andre"] mutableCopy];
NSLog(@"2: %@ ", person.siblings);
}
Output:
1: (Nikita)
2: (Nikita)
为什么在第二个示例中,当我更改siblings
的值时,它在person.siblings
中没有更改?
答案 0 :(得分:1)
从你的第二个例子:
siblings = [@[@"Andre"] mutableCopy];
您正在更改名为siblings
的本地变量以引用新对象。 siblings
对象的person
属性仍然引用旧数组。
以下是该行之前的内存:
以下是它的样子: