読者です 読者をやめる 読者になる 読者になる

Pebble's Diary

プログラマーの作業メモ

NSCopyingプロトコルに準拠する場合の実装メモ

NSCopyingプロトコルを実装する時に、いつも書き方を忘れているのでメモしておく。

@interface Bean : NSObject

@property (nonatomic,strong) NSString* country;
@end

@interface Coffee : NSObject

@property (nonatomic,assign) NSUInteger coffeeid;
@property (nonatomic,strong) NSString* name;
@property (nonatomic,strong) NSArray* size;
@property (nonatomic,strong) NSArray* beans1;
@property (nonatomic,strong) NSMutableArray* beans2;
@end

@implementation Bean
- (id)copyWithZone:(NSZone *)zone
{
    Bean* bean = [[[self class] allocWithZone:zone] init];
    if( bean ){
        bean->_country = [_country copyWithZone:zone];
    }
    return bean;
}
@end

@implementation Coffee
- (id)copyWithZone:(NSZone *)zone
{
    Coffee* coffee = [[[self class] allocWithZone:zone] init];
    if( coffee ){
        coffee->_coffeeid = _coffeeid;
        coffee->_name = [_name copyWithZone:zone];
        coffee->_size = [_size copyWithZone:zone];
        coffee->_beans1 = [[[_beans1 class] allocWithZone:zone] initWithArray:_beans1 copyItems:YES];
        coffee->_beans2 = [[[_beans2 class] allocWithZone:zone] initWithArray:_beans2 copyItems:YES];
    }
    return coffee;
}
@end