这是一个很有趣的问题,在Car2复制时候,CAR2的引擎复制了几次?为什么?
这个问题涉及到深浅复制,属性的应用,以及内存的整理等多方面。结果很有趣,答案是三次。
#import <Foundation/Foundation.h>
#import "Car.h"
int main(int argc, const char * argv[])
{
@autoreleasepool
{
Car *car = [[[Car alloc] init] autorelease];
NSLog(@"%@", car);
Car *car2 = [car copy];
[car2 release];
}
return 0;
}
#import <Foundation/Foundation.h>
#import "Engine.h"
#import "Wheel.h"
@interface Car : NSObject<NSCopying>
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSString* brand;
@property (nonatomic, copy) Engine *myengine;
@property (nonatomic, copy) Wheel *mywheel;
@end
#import "Car.h"
@implementation Car
-(id)copyWithZone:(NSZone*) zone
{
// 深复制
Car *car1 = [[[self class] allocWithZone:zone] init];
car1.name = [[_name copy] autorelease];
car1.brand = [[_brand copy] autorelease];
car1.myengine = [[_myengine copy] autorelease];
car1.mywheel = [[_mywheel copy] autorelease];
return car1;
}
- (id)init
{
if (self = [super init])
{
self.brand = @"奔驰";
self.name = @"GLK300";
// 这些值赋予属性的时候是通过copy的方式,故Wheel要通过alloc ->init -> copy 才能到达Car 的属性
self.mywheel = [[[Wheel alloc] init] autorelease];
self.myengine = [[[Engine alloc] init] autorelease];
}
return self;
}
- (NSString*)description
{
NSString* str = [NSString stringWithFormat:@"我是%@,我的名字是%@,我的引擎是%@,我的轮胎是%@", _brand , _name , _myengine , _mywheel];
return str;
}
- (void)dealloc
{
// 属性是指针变量,需要释放
[_mywheel release];
[_myengine release];
// 在定义中retain 可以释放
[_name release];
[_brand release];
[super dealloc];
}
@end
#import <Foundation/Foundation.h>
@interface Engine : NSObject<NSCopying>
@property (nonatomic,copy) NSString* brand;
@end
#import "Engine.h"
@implementation Engine
-(id)copyWithZone:(NSZone *)zone
{
// 浅复制
Engine *eng = [[[self class] allocWithZone:zone] init];
eng.brand = _brand;
NSLog(@"%@马达加上了!", _brand);
return eng;
}
-(id)init
{
self = [super init];
self.brand = @"V12";
return self;
}
-(NSString*)description
{
return [NSString stringWithFormat:@"%@", _brand];
}
@end
#import <Foundation/Foundation.h>
@interface Wheel : NSObject<NSCopying>
@property (nonatomic,copy) NSString* brand;
@end
#import "Wheel.h"
@implementation Wheel
-(id)copyWithZone:(NSZone *)zone
{
// 浅复制
Wheel *wheel2 = [[[self class] allocWithZone:zone] init] ;
wheel2.brand = _brand;
NSLog(@"%@轮胎加好了!", _brand);
return wheel2;
}
-(id)init
{
self = [super init];
self.brand = @"马牌";
return self;
}
-(NSString*)description
{
return [NSString stringWithFormat:@"%@", _brand];
}
@end