【发布时间】:2009-09-01 08:15:32
【问题描述】:
此代码有效:
猴子.h
@interface monkey : NSObject {
NSNumber *monkeyRanch;
}
@property (nonatomic, retain) NSNumber *monkeyRanch;
-(id) gatherTheMonkeys:(int)howmany;
猴子.m
@synthesize monkeyRanch;
-(id) gatherTheMonkeys:(int)howmany{
NSNumber *temp=[[NSNumber alloc] initWithInt:howmany];
monkeyRanch = temp;
[temp release];
return [monkeyRanch autorelease];
}
appDelegate.m
theMonkeys = [[monkey alloc] gatherTheMonkeys:3];
[window addSubview:[navigationController view]];
[window makeKeyAndVisible];
..和 theMonkeys 在 dealloc 中释放。仪器没有泄漏。
但是,如果我尝试使用NSMutable 数组而不是NSNumber:
猴子.h
@interface monkey : NSObject {
NSMutableArray *monkeyRanch;
}
@property (nonatomic, retain) NSMutableArray *monkeyRanch;
-(id) initTheMonkeys:(int)howmany;
猴子.m @synthesize monkeyRanch;
-(id) initTheMonkeys:(int)howmany{
monkeyRanch=[[NSMutableArray alloc] init];
NSNumber *imp =[[NSNumber alloc] initWithInteger:howmany];
[monkeyRanch addObject:imp];
[imp release];
return [monkeyRanch autorelease];
}
appDelegate
theMonkeys = [[monkey alloc] initTheMonkeys:3];
[theMonkeys retain];
这会在应用程序开始时导致(对象“猴子”)泄漏。
我尝试将initTheMonkeys 更改为以下内容:
NSMutableArray *temp=[[NSMutableArray alloc] init];
monkeyRanch=temp;
[temp release];
NSNumber *imp =[[NSNumber alloc] initWithInteger:howmany];
[monkeyRanch addObject:imp];
[imp release];
return [monkeyRanch autorelease];
但monkeyRanch 的保留计数在释放 temp 时变为零,应用程序愉快地崩溃了。
我做错了什么,我该如何解决?
【问题讨论】:
-
猴子牧场是什么鬼?那应该是“monkeyWrench”吗? :)
标签: iphone cocoa-touch memory-management