TA的每日心情 | 汗 2024-10-15 10:05 |
---|
签到天数: 372 天 [LV.9]以坛为家II
|
上一讲简述了拷贝的基本原理,这一讲以一个类进行说明浅拷贝的效果
1、创建一个类Car、使用<NSCopying>,<NSMutableCopying>协议对对象进行拷贝,自创的类必须实现拷贝中的 - (id)copyWithZone:(NSZone *)zone 方法或- (id)mutableCopyWithZone:(NSZone *)zone 方法;
2、修改拷贝对象中的值,这里区分copy与retain在对象操作中的不同点:car1 = car指向的是同一对象,car1 = [car copy]创建了另外一个对象,修改对象中的值不影响原来对象的值,但对象中的使用的其他对象不拷贝;
3、深拷贝则对对象引用的其他对象都进行拷贝(后续通过深拷贝说明);
SACar.h- //
- // SACar.h
- // Copy
- //
- // Created by yusian on 14-1-22.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface SACar : NSObject <NSCopying, NSMutableCopying>
- @property int year;
- @property (copy) NSString *name;
- @end
复制代码 SACar.m- //
- // SACar.m
- // Copy
- //
- // Created by yusian on 14-1-22.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import "SACar.h"
- @implementation SACar
- - (id) copyWithZone:(NSZone *)zone {
- SACar * c = [[[[self class] allocWithZone:zone] init] autorelease];
- c.name = self.name;
- c.year = self.year;
- return c;
- }
- - (id) mutableCopyWithZone:(NSZone *)zone {
- SACar * c = [[[[self class] allocWithZone:zone] init] autorelease];
- c.name = self.name;
- c.year = self.year;
- return c;
- }
- - (NSString *) description {
- return [NSString stringWithFormat:@"%@ age is %d", self.name, self.year];
- }
- - (void) dealloc {
- NSLog(@"%@ is dealloc", self.name);
- [super dealloc];
- }
- @end
复制代码 main.m- //
- // main.m
- // Copy
- //
- // Created by yusian on 14-1-22.
- // Copyright (c) 2014年 yusian. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #import "SACar.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
-
- SACar * car = [[[SACar alloc] init] autorelease];
- car.name = @"Cruze";
- car.year = 2013;
- NSLog(@"%@", car);
- SACar * car1 = [car copy];
- car1.name = @"Sonata";
- car1.year = 2014;
- NSLog(@"%@", car1);
-
- NSLog(@"%@ retainCount is %ld", car.name, car.retainCount);
- NSLog(@"%@ retainCount is %ld", car1.name, car1.retainCount);
-
- [car retain];
- NSLog(@"%@ retainCount is %ld", car.name, car.retainCount);
- NSLog(@"%@ retainCount is %ld", car1.name, car1.retainCount);
- [car release];
- }
- return 0;
- }
复制代码 输出结果:- 2014-01-22 20:14:08.733 Copy[1788:303] Cruze age is 2013
- 2014-01-22 20:14:08.735 Copy[1788:303] Sonata age is 2014
- 2014-01-22 20:14:08.735 Copy[1788:303] Cruze retainCount is 1
- 2014-01-22 20:14:08.735 Copy[1788:303] Sonata retainCount is 1
- 2014-01-22 20:14:08.736 Copy[1788:303] Cruze retainCount is 2
- 2014-01-22 20:14:08.736 Copy[1788:303] Sonata retainCount is 1
- 2014-01-22 20:14:08.736 Copy[1788:303] Sonata is dealloc
- 2014-01-22 20:14:08.737 Copy[1788:303] Cruze is dealloc
- Program ended with exit code: 0
复制代码 |
|