【发布时间】:2011-11-20 02:02:15
【问题描述】:
如果我想在我的代码中进行良好的内存管理,我需要知道对象的retaincount 是否应该始终为0。我从一本书中得到了以下代码。并且有一个声明 NSLog 称为 after release = 2,所以我应该再释放它 2 次以使 retaincount 为 0 吗?
#import <Foundation/NSObject.h>
#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSString.h>
#import <Foundation/NSArray.h>
#import <Foundation/NSValue.h>
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSNumber *myInt = [NSNumber numberWithInteger: 100];
NSNumber *myInt2;
NSMutableArray *myArr = [NSMutableArray array];
NSLog (@”myInt retain count = %lx”,
(unsigned long) [myInt retainCount]);
[myArr addObject: myInt];
NSLog (@”after adding to array = %lx”,
(unsigned long) [myInt retainCount]);
myInt2 = myInt;
NSLog (@”after asssignment to myInt2 = %lx”,
(unsigned long) [myInt retainCount]);
[myInt retain];
NSLog (@”myInt after retain = %lx”,
(unsigned long) [myInt retainCount]);
NSLog (@”myInt2 after retain = %lx”,
(unsigned long) [myInt2 retainCount]);
[myInt release];
NSLog (@”after release = %lx”,
(unsigned long) [myInt retainCount]);
[myArr removeObjectAtIndex: 0];
NSLog (@”after removal from array = %lx”,
(unsigned long) [myInt retainCount]);
[pool drain];
return 0;
}
程序输出
myInt 保留计数 = 1
添加到数组后 = 2
分配给 myInt2 = 2
保留后的 myInt = 3
保留后的 myInt2 = 3
发布后 = 2
从数组中删除后 = 1
更新
The following code was taken from the Apples memory management document。他们保留了一个 NSNumber 对象并且它从未被释放,这样可以吗?
- (void)setCount:(NSNumber *)newCount {
[newCount retain];
[_count release];
// Make the new assignment.
_count = newCount;
}
【问题讨论】:
-
请注意,myInt 和 myInt2 的保留计数是相同的,因为保留计数适用于对象,而不是指针变量,并且这两个指针变量都指向同一个对象。
-
请注意,在您的示例中,“释放后”的保留计数为 2,因为数组“拥有”一个计数,自动释放对象“拥有”一个计数。
-
请在 Stackoverflow 中搜索 retainCount,看看声誉超过 5000 分的程序员对此有何评价。
-
那么是不是需要释放数组所拥有的
retainCount呢?我认为我不必考虑释放自动释放对象“拥有”的计数,因为NSAutoreleasePool会处理它?
标签: iphone objective-c cocoa-touch