2013-11-21 5 views
2

copyWithZone을 구현하는 데있어 두 가지 방법이 조금 다릅니다. 그들은 다른가요?딥 복사 - copyWithZone의 두 구현이 다른가요?

첫 번째 코드 :

@interface Person : NSObject <NSCopying> 

@property (nonatomic,weak) NSString *name; 
@property (nonatomic,weak) NSString *surname; 
@property (nonatomic,weak) NSString *age; 

-(id) copyWithZone:(NSZone *)zone; 

@end 

//and 1st implementation 
@implementation Person 
-(id) copyWithZone:(NSZone *)zone 
{ 
Person *copy = [[self class] allocWithZone:zone]; 
copy.name = self.name; //should we use copy.name=[self.name copyWithZone: zone]; ? 
copy.age = self.age; 
copy.surname = self.surname; //here we make assignment or copying? 
return copy; 
} 
@end 

, 2 코드

@interface YourClass : NSObject <NSCopying> 
{ 
    SomeOtherObject *obj; 
} 

// In the implementation 
-(id)copyWithZone:(NSZone *)zone 
{ 
    // We'll ignore the zone for now 
    YourClass *another = [[YourClass alloc] init]; 
    another.obj = [obj copyWithZone: zone]; 

    return another; 
} 

서로 다른 경우, 그들에게 더 정확한 무엇? 1. 1 일에 [자아 수업]과 혼동합니다. 객관적인 C에서 메타 클래스에 대해 알고 있지만, 코드 덩어리에서 필요합니까? 2. copy.name = self.name; vs another.obj = [obj copyWithZone : zone] 위와 다른 점은 무엇입니까?

답변

2
  1. 약한 문자열 속성은 좋지 않습니다. 즉, 다른 누군가가 사용자의 문자열을 강력하게 참조한다는 의미입니다. 그렇지 않으면 할당이 취소됩니다.

하는 데는 보통의 좋은 지금있는 NSString을 할 생각 * 속성 사본 재산 : 관해서

@interface Person : NSObject <NSCopying> 

@property (nonatomic,copy) NSString *name; 

... 

//and 1st implementation 
@implementation Person 
-(id) copyWithZone:(NSZone *)zone 
{ 
Person *copy = [[self class] allocWithZone:zone]; 
copy.name = self.name; //assigning here is same as coping, should be enough 

:이 경우

[self class] 

메타하지 클래스이 반환되고 클래스 만이 사본 호출은 다형성을 가지며 Person 서브 클래스에서 사용될 수 있습니다. 그 이외의 경우는, copy는 항상 Person를 돌려 주지만, 서브 클래스의 메소드 복사는 불려갑니다.

copy.name = self.name; 

another.obj = [obj copyWithZone: zone] 

첫 번째 경우는 속성에 할당됩니다 -이 속성 유형에 따라 처리하는 방법. 복사 속성의 경우 -이 두 표현식은 동일합니다. SomeOtherObject도 딥 복사본을 구현하므로 두 번째 대소 문자가 올바르게 처리됩니다.

https://developer.apple.com/library/mac/documentation/general/conceptual/devpedia-cocoacore/ObjectCopying.html