1

我是 Objective-C 的新手。这是我在这里的第一篇文章。我创建了一个单例来管理我的应用程序接口到数据库。为了简单起见,我使用 NSMutableArray 作为 ivar。正如您将在下面的代码和日志输出中看到的,在将其分配给 NSMutableArray 对象之前保留计数为 0,然后在分配后保留计数为 2。

我不清楚为什么会这样。是因为 [NSMutableArray arrayWithObject:(id)] 创建了一个保留计数为 1 的对象,然后赋值 self.dataList 增加了保留计数?调用释放一次是否安全?这似乎不是正确的做法。

这里是源

#import <Foundation/Foundation.h>


@interface DataInterfaceObject : NSObject {
    NSMutableArray *dataList;

}

@property (nonatomic, retain) NSMutableArray *dataList;

+ (id) sharedAlloc;

@end

...

#import "DataInterface.h"

static DataInterfaceObject *sharedDataInterfaceObject = nil;

@implementation DataInterfaceObject

@synthesize dataList;

+ (id) sharedAlloc {    
    @synchronized(self) {
        if (sharedDataInterfaceObject == nil) 
            sharedDataInterfaceObject = [super alloc];
    }
    return sharedDataInterfaceObject;
}

+ (id) alloc {
    return [[self sharedAlloc] init];
}

- (id)init 
{
    @synchronized(self) {
        NSLog(@"In DataInterface init 1, RetainCount for dataList is %d", [self.dataList retainCount]);
        if (dataList == nil) {
            self = [super init];
            if (self) {
                //Instantiate list
                NSLog(@"In DataInterface init 2, RetainCount for dataList is %d", [self.dataList retainCount]);
                self.dataList = [NSMutableArray arrayWithObjects:@"Dog", @"Cat", @"Homer", @"Vanessa", @"Tour Eiffel", @"Ball", @"Lettuce", nil];
                NSLog(@"In DataInterface init 3, RetainCount for dataList is %d", [self.dataList retainCount]);
            }
        }
    }
    return self;
}

- (void)dealloc 
{
    [dataList release];
    [super dealloc];
}

@end

日志显示以下内容:

2011-04-06 21:18:26.931 jobs[11672:207] initislized
2011-04-06 21:18:26.933 jobs[11672:207] In DataInterface init 1, RetainCount for dataList is 0
2011-04-06 21:18:26.934 jobs[11672:207] In DataInterface init 2, RetainCount for dataList is 0
2011-04-06 21:18:26.934 jobs[11672:207] In DataInterface init 3, RetainCount for dataList is 2
4

3 回答 3

4

不要使用保留计数进行调试,你会发疯的。如果您遇到内存泄漏或过度释放问题,请确保您遵循内存管理规则。

可可核心竞争力

Cocoa With Love 有一篇关于在 Cocoa 中创建单例的好文章。

于 2011-04-07T04:56:39.897 回答
4

编码:

[NSMutableArray arrayWithObjects:@"Dog", @"Cat", @"Homer", @"Vanessa",
    @"Tour Eiffel", @"Ball", @"Lettuce", nil];

创建一个保留计数为 1 的自动释放变量,该变量将在未来某个时间释放。您的属性也调用了保留,因此在调用 print 语句时对象的保留计数为 2,然后很快将减少到 1。

于 2011-04-07T04:59:30.757 回答
2

Yes, the reason it goes straight to two is that a) you create the object and b) you retain the object by assigning it to self.dataList. You're not responsible for the creation of the object, though, since you didn't call +alloc, so it's fine for your -dealloc to release dataList only once.

That said, @Terry Wilcox is right: don't look at -retainCount.

于 2011-04-07T05:00:17.433 回答