不务正业之OC(四)–memory leak修复

方法1:只需要修改Bike.m、main.m,setTire方式时,使用retain,使用引用计数加1,_tire获得对象所有权,_tire要负责释放tire对象,所以当释放Bike时,dealloc方法中调用[_tire release];main.m增加[b release];

#import "Bike.h"
@implementation Bike
- (void) setTire:(Tire *) tire{
    _tire = [tire retain]; //转交所有权
}
 
- (Tire *) Tire{
    return _tire;
}
 
- (void) dealloc{
    [_tire release]//当销毁t的对象时,同时销毁b对象
    NSLog(@"Bike is disappear!");
    [super dealloc];
}
@end
#import <Foundation/Foundation.h>
#import "Bike.h"
#import "Tire.h"
 
int main(int argc, const char * argv[])
{
 
    @autoreleasepool {
        Tire *t = [[Tire alloc] init];
        Bike *b = [[Bike alloc] init];
        [t setPressure:22];
        [b setTire:t];
        [t release];
        NSLog(@"bike pressure is %d",[[b Tire] Pressure]);
        [b release];//把bike对象释放掉
    }
    return 0;
}
2014-04-27 21:32:35.049 MemoryLeakDemo[10957:303] bike pressure is 22
2014-04-27 21:32:35.051 MemoryLeakDemo[10957:303] Tire is disappear!
2014-04-27 21:32:35.051 MemoryLeakDemo[10957:303] Bike is disappear!

方法2:@synthesize @property实现

//  Tire.h
//  MemoryManage
 
 
#import <Foundation/Foundation.h>
 
@interface Tire : NSObject
{
    int pressure;
}
@property int pressure;
@end
//  Tire.m
//  MemoryManage
 
 
#import "Tire.h"
 
@implementation Tire
@synthesize pressure;
- (void) dealloc{
    NSLog(@"Tire is disappear!");
    [super dealloc];
}
@end
//  Bike.h
//  MemoryManage
 
#import <Foundation/Foundation.h>
#import "Tire.h"
@interface Bike : NSObject
{
    Tire *_tire;
}
@property (retain)Tire* _tire; //retain就能获得oneTire对象所有权
@end
//  Bike.m
//  MemoryManage
 
#import "Bike.h"
 
@implementation Bike
@synthesize _tire;
 
- (void) dealloc{
    [_tire release];
    NSLog(@"Bike is disappear!");
    [super dealloc];
}
@end
//  main.m
//  MemoryManage
 
#import <Foundation/Foundation.h>
#import "Bike.h"
#import "Tire.h"
 
int main(int argc, const char * argv[])
{
 
    @autoreleasepool {
        Tire *oneTire = [[Tire alloc] init];
        oneTire.pressure = 22;
        Bike *bike = [[Bike alloc] init];
        bike._tire = oneTire;
        [oneTire release];
        NSLog(@"bike is pressure %d",bike._tire.pressure);
        [bike release];
    }
    return 0;
}

结果:

2014-04-27 21:49:54.286 MemoryManage[11009:303] bike is pressure 22
2014-04-27 21:49:54.288 MemoryManage[11009:303] Bike is disappear!  --这里为什么是Bike先打印的?异步的?
2014-04-27 21:49:54.288 MemoryManage[11009:303] Tire is disappear!

Post a Comment