在学习移动互联Objective C视频,内存管理部门时遇到一个问题,下边红色的代码,视频中显示调试是会出错的,因为在调用[[apply cpu] CId]之前 cpu所指向的对象已经被释放,可是我照着视频中的代码做,怎么调试都是运行正常,不出错,奇了怪了,难呢是因为我的XCode是最新版的,请求高手解答。
#import <Foundation/Foundation.h>
#import "CPU.h"
#import "Laptop.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
CPU *powerPC = [[CPU alloc] init]; //创建CPU对象
[powerPC setCID:101]; //设置CID
Laptop *apple = [[Laptop alloc]init]; //创建Laptop对象
[apple setCPU:powerPC]; //设置CPU对象
[powerPC release]; //释放CPU对象
NSLog(@"apple cpu id:%d",[[apple cpu] CID]); //调用已经被释放了的对象的方法
}
return 0;
}下边是类的声明和定义
//CPU.h
#import <Foundation/Foundation.h>
@interface CPU : NSObject
{
@private int _cID;
}
- (void) setCID:(int) cID;
- (int) CID;
@end//CPU.m
#import "CPU.h"
@implementation CPU
- (void) setCID:(int) cID
{ _cID = cID; }
- (int) CID
{ return _cID; }//Laptop.h
#import <Foundation/Foundation.h>
@class CPU;
@interface Laptop : NSObject
{
@private
CPU *_cpu;
}
- (void) setCPU:(CPU *) cpu;
- (CPU*) cpu;
@end//Laptop.m
#import "Laptop.h"
@implementation Laptop
- (void) setCPU:(CPU *) cpu
{
_cpu = cpu;
}
- (CPU*) cpu
{
return _cpu;
}
-(void) dealloc
{
NSLog(@"laptop dead");
[super dealloc];
}
@end
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货