Copy方法

[table]
|NSArray NSMutableArray| copy| NSArray
|NSArray NSMutableArray| mutableCopy| NSMutableArray
|NSDictionary NSMutableDictionary| copy| NSDictionary
|NSMutableDictionary NSDictionary| mutableCopy| NSMutableDictionary
[/table]


//
// 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值