//
// main.m
// 04-set方法的内存管理分析
//
// Created by apple on 14-3-17.
//
//
#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;
}
//
// Person.m
// 01-手动内存管理基本概念
//
// Created by apple on 14-3-17.
//
//
#import "Person.h"
//配对原则:new alloc retain 对应一个release,autorelease
@implementation Person
- (void)setName:(NSString *)name
{
if (_name != name)
{
[_name release];
_name = [name retain];
}
}
- (NSString *)name
{
return _name;
}
//解决三个问题:1,set多个不同car的时候,内存泄漏[ [_car release];//[nil release];]
2,set相同car的时候,野指针 [ if (_car != car)]
3,调用方法是提前被销毁 [_car = [car retain];]
- (void)setCar:(Car *)car
{
if (_car != car)
{ //c1 0
//relese旧值
[_car release];//[nil release];
//c2 2
//retain新值
_car = [car retain];
}
}
- (Car *)car
{
return _car;
}
- (void)drive
{
[_car run];
}
- (void)dealloc
{
//目的是要保证在p对象存在的时候,car对象一定存在
//对象p被销毁的时候,
//0
//c2 0
[_car release];
[_name release];
[super dealloc];
NSLog(@"Person 被销毁了");
}
@end