*我肯定需要休息一下...原因很简单-未分配数组...感谢您的帮助。由于这个尴尬的错误,我标记了我的帖子以将其删除。我认为这对用户没有帮助;)*
我刚刚尝试在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中的值相同。
最佳答案
创建单例的标准方法是...
单例
@interface MySingleton : NSObject
+ (MySingleton*)sharedInstance;
@end
单例
#import "MySingleton.h"
@implementation MySingleton
#pragma mark - singleton method
+ (MySingleton*)sharedInstance
{
static dispatch_once_t predicate = 0;
__strong static id sharedObject = nil;
//static id sharedObject = nil; //if you're not using ARC
dispatch_once(&predicate, ^{
sharedObject = [[self alloc] init];
//sharedObject = [[[self alloc] init] retain]; // if you're not using ARC
});
return sharedObject;
}
@end
关于ios - objective-c -单例实现示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15383452/