I'm new to Objective-C. This is my first post here. I created a singleton for the purpose of managing my applications interface to a database. To start out simple, I have used an NSMutableArray as an ivar. As you will see in the code below and the log output, the retain count is 0 before it is assigned to an NSMutableArray object, and then the retain count is 2 after the assignment.
I am not clear why this happens. Is it because the [NSMutableArray arrayWithObject:(id)] creates an object with a retain count of one and then the assignment self.dataList increments the retain count? Is it safe to call release once? That doesn't seem like the right thing to do.
Here is the source
#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
The log shows the following:
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
The code:
[NSMutableArray arrayWithObjects:@"Dog", @"Cat", @"Homer", @"Vanessa",
@"Tour Eiffel", @"Ball", @"Lettuce", nil];
Creates an autoreleased variable with a retain count of 1 that will be released sometime in the future. Your property also calls retain so the object will have a retain count of 2 when the print statement is called and then will soon be reduced to 1.