我是 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