*我绝对需要休息...原因很简单-未分配数组...感谢您的帮助。由于那个令人尴尬的错误,我标记了我的帖子以删除它。我觉得它对用户没有用 ;) *
我刚刚尝试在 iOS 中创建一个单例类,但我可能犯了一个错误。代码(不需要 ARC):
#import "PeopleDatabase.h"
#import "Person.h"
#import <Foundation/Foundation.h>
@interface PeopleDatabase : NSObject{objetive
NSMutableArray* _arrayOfPeople;
}
+(PeopleDatabase *) getInstance;
@property (nonatomic, retain) NSMutableArray* arrayOfPeople;
@end
--
@implementation PeopleDatabase
@synthesize arrayOfPeople = _arrayOfPeople;
static PeopleDatabase* instance = nil;
-(id)init{
if(self = [super init]) {
Person* person = [[[Person alloc] initWithName:@"John" sname:@"Derovsky" descr:@"Some kind of description" iconName:@"johnphoto.png" title:Prof] retain];
[_arrayOfPeople addObject:person];
NSLog(@"array count = %d", [_arrayOfPeople count]); // <== array count = 0
[person release];
}
return self;
}
+(PeopleDatabase *)getInstance {
@synchronized(self)
{
if (instance == nil)
NSLog(@"initializing");
instance = [[[self alloc] init] retain];
NSLog(@"Address: %p", instance);
}
return(instance);
}
-(void)dealloc {
[instance release];
[super dealloc];
}
@end
像这里调用 getInstance 时:
PeopleDatabase *database = [PeopleDatabase getInstance];
NSLog(@"Adress 2: %p", database);
地址 2 的值与 getInstance 中的值相同。