//
// Computer.h
// OC基础学习
//
// Created by 麦子 on 15/5/23.
// Copyright (c) 2015年 麦子. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Computer : NSObject<NSCopying>
@property(nonatomic,retain) NSString *name;
@property(nonatomic,retain) NSString *address;
+(void)checkCopy;
@end
//
// Computer.m
// OC基础学习
//
// Created by 麦子 on 15/5/23.
// Copyright (c) 2015年 麦子. All rights reserved.
//
#import "Computer.h"
/*******
复制对象概念:
重新在内存中开辟一块空间,复制分为浅复制和深复制。
1. 浅复制对其中的对象属性不会复制,不回重新开辟空间。 这个只是多了一个引用牵着其中的属性,指向的同一个地址。(就是retain)
2. 深复制,对其中的对象属性都会重现开辟空间。这个就是两个不同的地址。
条件: 对象具备复制功能,必须实现<NSCopying>协议,<NSSMutableCopying>协议,
常用的可复制对象有: NSNumber,NSString,NSArray,NSDictionary,NSMutableDictionay,
NSMutableArray,NSMutableString
复制对象的种类
copy:产生对象的副本是不可变的。(不管你本身原来是可变还是不可变的。只认方法)
mutableCopy:产生的对象副本是可变的。
*/
@implementation Computer
/***测试Copy的作用
结论:多了一个变量指向原来的地址*/
+(void)checkCopy{
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
for (int i = 0; i < 3; i++) {
NSObject *object = [[NSObject alloc]init];
[mutableArray addObject:object];
[object release];
}
for (NSObject *o in mutableArray) {
NSLog(@"复制之前:retainCounut:%lu",[o retainCount]); // 1
}
NSArray *array = [mutableArray copy];
for (NSObject *o in array) {
NSLog(@"复制之后:retainCount:%lu",[o retainCount]); // 2
}
// 这里的结果说明,在copy中,只是对,其中对象和copy的对象都是引用相同的内存,这里的copy就相当于retain,多了一个变量指向这个内存。
}
-(id)copyWithZone:(NSZone *)zone{
Computer *computer = [[[self class] allocWithZone:zone] init];
/***浅拷贝***/
//computer.name = _name;
//computer.address = _address;
/***深拷贝*/
computer.name = [_name copy];
computer.address = [_address copy]; // 区别就是属性是否copy
return computer;
};
@end
/**对象复制*/
// [Computer checkCopy];
Computer *computer = [[Computer alloc] init];
Computer *newComputer = [computer copy];
NSLog(@"地址computer---%p,地址newCompeter----%p",computer,newComputer);
NSLog(@"属性---%p,new 属性%p",computer.name,newComputer.name); // 地址相同,浅拷贝。
// 深拷贝中,也是一样的。 这是在 foundation可复制的对象中, 他做了优化,当我们copy的是一个不可变的对象时,他的作用就相当于retain(cocoa做了优化)
2015-05-25 20:20:37.571 OC基础学习[756:60157]复制之前:retainCounut:1
2015-05-25 20:20:37.572 OC基础学习[756:60157]复制之前:retainCounut:1
2015-05-25 20:20:37.572 OC基础学习[756:60157]复制之前:retainCounut:1
2015-05-25 20:20:37.573 OC基础学习[756:60157]复制之后:retainCount:2
2015-05-25 20:20:37.573 OC基础学习[756:60157]复制之后:retainCount:2
2015-05-25 20:20:37.573 OC基础学习[756:60157]复制之后:retainCount:2
2015-05-25 20:20:37.573 OC基础学习[756:60157]地址computer---0x100100de0,地址newCompeter----0x100100e00
2015-05-25 20:20:37.573 OC基础学习[756:60157]属性---0x0,new属性0x0
同时,我们在属性设置的时候,直接设置为
@property(nonatomic,copy) NSString *name; 那么在后面,也就是直接 computer.name = _name; 这样就可以了。这个设置为copy,默认会在set的方法中,调用copy的方法。