//
// main.m
// set方法的内存管理分析
//
// 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-手动内存管理基本概念
//
// Created by apple on 14-3-17.
//
//
#import <Foundation/Foundation.h>
@interface Car : NSObject
@property int speed;
- (void)run;
@end
//
// Car.m
// 01-手动内存管理基本概念
//
// Created by apple on 14-3-17.
//
//
#import "Car.h"
@implementation Car
- (void)dealloc
{
[super dealloc];
NSLog(@"Car 被销毁了 %d速度",_speed);
}
- (void)run
{
NSLog(@"汽车跑起来了");
}
@end
//
// Person.h
// 01-手动内存管理基本概念
//
// 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-手动内存管理基本概念
//
// 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;
}
//面试笔试,出题率非常高
- (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
版权声明:本文为博主原创文章,未经博主允许不得转载。