//
Main.m
Memory management analysis of Set method
//
Created by admin on 15/8/5.
Copyright (c) 2015 admin. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[]) {
@autoreleasepool {
P 1
person * p = [[Person alloc] init];
C1 1
Car * C1 = [[Car alloc] init];
C1.speed = 100;
C1 2
[P SETCAR:C1];
[P Drive];
C1 1
[C1 release];
/*
[P SETCAR:C1];
[P Drive];
C2 1
Car * C2 = [[Car alloc] init];
C2.speed = 350;
C2 2
[P SETCAR:C2];
[P Drive];
C2 1
[C2 release];
P 0
[P release];
}
return 0;
}
//
Car.h
01-Manual memory management Basic concepts
//
Created by Apple on 14-3-17.
//
//
#import <Foundation/Foundation.h>
@interface Car:nsobject
@property int speed;
-(void) run;
@end
//
Car.m
01-Manual memory management Basic concepts
//
Created by Apple on 14-3-17.
//
//
#import "Car.h"
@implementation Car
-(void) dealloc
{
[Super Dealloc];
NSLog (@ "Car was destroyed by%d speed", _speed);
}
-(void) run
{
NSLog (@ "The car ran up");
}
@end
//
Person.h
01-Manual memory management Basic concepts
//
Created by Apple on 14-3-17.
//
//
#import <Foundation/Foundation.h>
#import "Car.h"
@interface Person:nsobject
{
Car * _CAR;
NSString * _NAME;
}
-(void) SetName: (NSString *) name;
-(NSString *) name;
-(void) Setcar: (car *) car;
-(car *) car;
-(void) drive;
@end
//
Person.m
01-Manual memory management Basic concepts
//
Created by Apple on 14-3-17.
//
//
#import "Person.h"
Pairing principle: New alloc retain corresponds to a release,autorelease
@implementation person
-(void) SetName: (NSString *) name
{
if (_name! = name)
{
[_name release];
_name = [name retain];
}
}
-(NSString *) name
{
return _name;
}
Interview written test, the rate is very high
-(void) Setcar: (Car *) car
{
if (_car! = car)
{//C1 0
Relese old value
[_car Release];//[nil release];
C2 2
Retain new value
_car = [car retain];
}
}
-(CAR *) car
{
return _car;
}
-(void) drive
{
[_car Run];
}
-(void) dealloc
{
The goal is to ensure that when the P object exists, the car object must exist
When the object P is destroyed,
0
C2 0
[_car release];
[_name release];
[Super Dealloc];
NSLog (@ "person has been destroyed");
}
@end
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The memory management analysis of the OC_ set method of the small white Learning Development (IOS) (2015-08-04)