Objective-C object replication simple implementation

Original link: http://www.cnblogs.com/yang3wei/archive/2012/10/06/2739341.html

Reprinted from: http://mobile.51cto.com/iphone-277001.htm

Objective-C object replication simple implementation of this article is to introduce the content, but also the line of Objective-C  is not too unfamiliar, let's look at the content.

Foundation system objects (NSString, NSArray, etc.)

Only to comply with the agreement NSCopying class can send a message copy

Only to comply with the agreement NSMutableCopying class can send a message mutableCopy

copy and mutableCopy difference is the return copy of the object can not be changed, but returned after mutableCopy can be modified objects .

The two methods to copy objects will need to be manually released.

Self-righteousness defined Class

After the self-righteousness given Class also need to implement NSCopying collusion or NSMutableCopying agreement, which objects to provide copy function. Code

TestProperty.h

//
//  TestProperty.h
//  HungryBear
//
//  Created by Bruce Yang on 12-10-6.
//  Copyright (c) 2012年 EricGameStudio. All rights reserved.
//

@interface TestProperty : NSObject <NSCopying> {
    NSString* _name;
    NSString* _password;   
    NSMutableString* _interest;
    NSInteger _myInt;
}

@property (retain, nonatomic) NSString* name;
@property (retain, nonatomic) NSString* password;  
@property (retain, nonatomic) NSMutableString* interest;
@property NSInteger myInt;

@end

TestProperty.mm

//
//  TestProperty.mm
//  HungryBear
//
//  Created by Bruce Yang on 12-10-6.
//  Copyright (c) 2012年 EricGameStudio. All rights reserved.
//

#import "TestProperty.h"

@implementation TestProperty

@synthesize name = _name;
@synthesize password = _password;
@synthesize interest = _interest;
@synthesize myInt = _myInt;

-(id) copyWithZone:(NSZone*)zone {
    TestProperty* newObj = [[[self class] allocWithZone:zone] init];
    newObj.name = _name;
    newObj.password = _password;
    newObj.myInt = _myInt;
    
    // 深复制~
    NSMutableString* tmpStr = [_interest mutableCopy];
    newObj.interest = tmpStr;
    [tmpStr release];
    
    // 浅复制~
//    newObj.interest = _interest;
    
    return newObj;
}  

-(void) dealloc {
    self.name = nil;
    self.password = nil;
    self.interest = nil;
    [super dealloc];
}

@end

Reproduced in: https: //www.cnblogs.com/yang3wei/archive/2012/10/06/2739341.html

Guess you like

Origin blog.csdn.net/weixin_30563917/article/details/94783120