2014-11-06 3 views
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에서 변경 되었습니까? 두 번째 예에서

답변

1

:

siblings = [@[@"Andre"] mutableCopy]; 

당신은 새로운 객체를 참조 할 siblings을 명명 된 지역 변수 변경됩니다. person 개체의 siblings 속성은 여전히 ​​이전 배열을 참조합니다. 여기

메모리가 줄 앞에 모습입니다 :

before

를 그리고 여기의 모습입니다 후 :

after