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

创建两个类:Bike和Tire,自行车的其中一部件轮胎

//  Tire.h
//  MemoryLeakDemo
#import <Foundation/Foundation.h>
 
@interface Tire : NSObject
{
  int _pressure;//设置轮胎的胎压
}
 
- (void) setPressure:(int) pressure;//这边暂时不用property,synthesize
- (int) Pressure;
@end
//  Tire.m
//  MemoryLeakDemo
 
#import "Tire.h"
 
@implementation Tire
- (void) setPressure:(int) pressure{
    _pressure = pressure;
}
 
- (int) Pressure{
    return _pressure;
}
 
- (void) dealloc{
    NSLog(@"Tire is disappear!");
    [super dealloc];
}
@end
//  Bike.h
//  MemoryLeakDemo
 
#import <Foundation/Foundation.h>
@class Tire;
 
@interface Bike : NSObject
{
    Tire *_tire;
}
- (void) setTire:(Tire *) tire;
- (Tire *) Tire;
 
@end
//  Bike.m
//  MemoryLeakDemo
 
#import "Bike.h"
 
@implementation Bike
- (void) setTire:(Tire *) tire{
    _tire = tire;
}
 
- (Tire *) Tire{
    return _tire;
}
 
- (void) dealloc{
    NSLog(@"Bike is disappear!");
    [super dealloc];
}
@end
//  main.m
//  MemoryLeakDemo
 
#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]; //释放t对象,导致t对象引用计数为0,对象销毁
        NSLog(@"bike pressure is %d",[[b Tire] Pressure]);//还在访问销毁的对象,Xcode5.1居然能成功访问?Xcode4.3肯定不行的呀。
    }
    return 0;
}

运行结果:
2014-04-27 20:51:53.447 MemoryLeakDemo[10810:303] Tire is disappear!
2014-04-27 20:51:53.449 MemoryLeakDemo[10810:303] bike pressure is 22


Post a Comment