下面是我在练习代码时遇到的问题:通过分析发现有内存泄露,但是运行结果显示 都销毁了,请大神指点,谢谢!
Car.h
#import <Foundation/Foundation.h>
@interface Car : NSObject @property (nonatomic,readwrite,assign) int speed; -(void)run; @end
Car.m
#import "Car.h"
@implementation Car - (void)dealloc { //先让子类销毁 NSLog(@"\n速度为%d的Car已销毁",_speed); //再让父类销毁 [super dealloc]; } -(void)run { NSLog(@"\n车正在以%d的速度行驶",_speed); } @end
Person.h
#import <Foundation/Foundation.h> #import "Car.h" @interface Person : NSObject @property (nonatomic,readwrite,retain) Car *car; //方法 -(void)driver; @end
Person.m
#import "Person.h"
@implementation Person -(void)driver { [_car run]; } - (void)dealloc { [_car dealloc]; NSLog(@"\nPerson已销毁"); [super dealloc]; } @end
main.m
#import <Foundation/Foundation.h> #import "Person.h" int main(int argc, const char * argv[]) { @autoreleasepool { // 用Person类实例化一个对象WR Person *WR=[[Person alloc] init]; //WR:1 NSLog(@"Person->%lu",WR.retainCount); //用Car类实例化一个对象BMW Car *BMW=[Car new]; //BMW:1 NSLog(@"BMW->%lu",BMW.retainCount); //给实例变量赋值 BMW.speed=100;
//给WR赋一辆车 [WR setCar:BMW]; //BMW:1->2 NSLog(@"BMW->%lu",BMW.retainCount); //调用方法driver [WR driver];
//内存管理原则:谁创建,谁release [BMW release]; //BMW:2->1 NSLog(@"BMW->%lu",BMW.retainCount); [WR driver];
//重新给WR传一辆车byd Car *byd=[Car new]; NSLog(@"byd->%lu",byd.retainCount);//byd:1 byd.speed=70; [WR setCar:byd]; NSLog(@"byd->%lu",byd.retainCount);//byd:1->2 [WR driver]; [WR driver]; //谁创建,谁release // [byd release]; NSLog(@"byd->%lu",byd.retainCount);//byd:2->2 现在的bydRetainCount=2,当执行完[WR release]以后,bydRetainCount=1,也不应该打印出 “速度为70的Car已销毁” [WR driver]; //内存管理原则:谁创建,谁release [WR release]; } return 0; }
打印输出: byd->1
速度为200的Car已销毁 byd->2 车正在以70的速度行驶
车正在以70的速度行驶 byd->2
车正在以70的速度行驶
速度为70的Car已销毁 我的分析是:不应该打印出这句话,因为此时的 bydRetainCount=1
Person已销毁
|