1
개체 속성에 변경할 수있는 하위 클래스가있는 경우 변수가 strong
대신 copy
이되어야 클래스가 허용하지 않고 변수가 변경되지 않도록해야합니다. 원칙을 완전히 이해하기 위해 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)
I가 siblings
의 값을 변경할 때, 두 번째 예에서는 그렇지를되는 이유 person.siblings
에서 변경 되었습니까? 두 번째 예에서