*間違いなく休憩が必要です... 原因は単純です - 配列が割り当てられていませんでした... 助けてくれてありがとう。その恥ずかしい間違いのために、私はそれを削除するために私の投稿にフラグを立てました. ユーザーにとって役に立たないと思います;)*
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 と同じ値です。