This is an interesting question. How many times did the Car2 engine replicate during CAR2 replication? Why?
This issue involves in-depth replication, attribute applications, and memory sorting. The result is interesting. The answer is three times.
#import
#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
#import "Engine.h"#import "Wheel.h"@interface Car : NSObject
@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 {// deep copy 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 = @ "Benz"; self. name = @ "GLK300"; // when these values are assigned to attributes, they are copied. Therefore, Wheel must use alloc-> init-> copy to reach the Car property self. mywheel = [[[Wheel alloc] init] autorelease]; self. myengine = [[Engine alloc] init] autorelease];} return self;}-(NSString *) description {NSString * str = [NSString stringWithFormat: @ "I am % @, my name is % @, my engine is % @, and my tires are % @ ", _ brand, _ name, _ myengine, _ mywheel]; return str ;} -(void) dealloc {// The attribute is a pointer variable and you need to release [_ mywheel release]; [_ myengine release]; // In the definition, retain can release [_ name release]; [_ brand release]; [super dealloc];} @ end
#import
@interface Engine : NSObject
@property (nonatomic,copy) NSString* brand;@end
# Import "Engine. h "@ implementation Engine-(id) copyWithZone :( NSZone *) zone {// light copy Engine * eng = [[[self class] allocWithZone: zone] init]; eng. brand = _ brand; NSLog (@ "% @ added to the motor! ", _ Brand); return eng;}-(id) init {self = [super init]; self. brand = @ "V12"; return self;}-(NSString *) description {return [NSString stringWithFormat: @ "% @", _ brand];} @ end
#import
@interface Wheel : NSObject
@property (nonatomic,copy) NSString* brand;@end
# Import "Wheel. h "@ implementation Wheel-(id) copyWithZone :( NSZone *) zone {// light copy Wheel * wheel2 = [[[self class] allocWithZone: zone] init]; wheel2.brand = _ brand; NSLog (@ "% @ tire added! ", _ Brand); return wheel2;}-(id) init {self = [super init]; self. brand = @ "horse"; return self;}-(NSString *) description {return [NSString stringWithFormat: @ "% @", _ brand];} @ end