NSArray NSMutableArray | copy | NSArray |
NSArray NSMutableArray | mutableCopy | NSMutableArray |
NSDictionary NSMutableDictionary | copy | NSDictionary |
NSMutableDictionary NSDictionary | mutableCopy | NSMutableDictionary |
// // main.m // MutableCopy // // Created by rayln on 13-9-13. // Copyright (c) 2013年 rayln. All rights reserved. // #import <Foundation/Foundation.h> #import "Student.h" void copy(){ //若要copy自定义的对象,必须实现NSCopying协议, 并且实现copyWithZone方法 Student *stu = [[Student alloc] init]; Student *stu1 = [stu copy]; [stu release]; [stu1 release]; } int main(int argc, const char * argv[]) { @autoreleasepool { #pragma mark - mutablecopy 深拷贝 NSString *str1 = @"100"; NSMutableString *str2 = [str1 mutableCopy]; //copy出来的对象需要释放内存 [str2 release]; #pragma mark - copy 浅拷贝 NSString *string1 = @"101"; NSString *string2 = [string1 copy]; //string1对象和string2对象是同一个对象,因为NSString本来就是不可变的 [string2 release]; Student *stu = [[Student alloc] init]; NSMutableString *name = [[NSMutableString alloc] initWithString:@"rayln"]; NSMutableString *passport = [[NSMutableString alloc] initWithString:@"445281"]; stu.name = name; stu.passport = passport; [name appendString:@"Guan"]; [passport appendString:@"1983"]; //由此可见,retain策略的话,外面重新符值,student的name也会改变 //使用copy策略的话,外面重新符值,student的passport还是没有改变 NSLog(@"Student.name:%@ name:%@", stu.name, name); NSLog(@"Student.passport:%@ passport:%@", stu.passport, passport); [name release]; [passport release]; [stu release]; } return 0; }
Student.h
// // Student.h // MutableCopy // // Created by rayln on 13-9-13. // Copyright (c) 2013年 rayln. All rights reserved. // #import <Foundation/Foundation.h> @interface Student : NSObject <NSCopying> //建议NSString对象用copy,其他对象用retain策略 @property (nonatomic, retain) NSString *name; @property (nonatomic, copy) NSString *passport; @end
Student.m
// // Student.m // MutableCopy // // Created by rayln on 13-9-13. // Copyright (c) 2013年 rayln. All rights reserved. // #import "Student.h" @implementation Student //实现copyWithZone方法,使用copy方法必须实现他 - (id)copyWithZone:(NSZone *)zone{ Student *stu = [[Student allocWithZone:zone] init]; stu.name = self.name; stu.passport = self.passport; return stu; } - (void)dealloc{ [_name release]; [_passport release]; [super dealloc]; } @end