我的单例访问器方法通常是以下的一些变体:
static MyClass *gInstance = NULL;
+ (MyClass *)instance
{
@synchronized(self)
{
if (gInstance == NULL)
gInstance = [[self alloc] init];
}
return(gInstance);
}
Run Code Online (Sandbox Code Playgroud)
我可以做些什么来改善这个?
我正在尝试直接实现一个类,即NSObject在使用它的应用程序运行的整个过程中只能有一个实例可用.
目前我有这种方法:
// MyClass.h
@interface MyClass : NSObject
+(MyClass *) instance;
@end
Run Code Online (Sandbox Code Playgroud)
并实施:
// MyClass.m
// static instance of MyClass
static MyClass *s_instance;
@implementation MyClass
-(id) init
{
[self dealloc];
[NSException raise:@"No instances allowed of type MyClass" format:@"Cannot create instance of MyClass. Use the static instance method instead."];
return nil;
}
-(id) initInstance
{
return [super init];
}
+(MyClass *) instance {
if (s_instance == nil)
{
s_instance = [[DefaultLiteralComparator alloc] initInstance];
}
return s_instance;
}
@end
Run Code Online (Sandbox Code Playgroud)
这是完成这项任务的正确方法吗? …
*我肯定需要休息......原因很简单 - 数组没有分配...感谢您的帮助.由于这个令人尴尬的错误,我标记了我的帖子以删除它.我觉得它对用户没用;)*
我刚刚尝试在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
Run Code Online (Sandbox Code Playgroud)
-
@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 …Run Code Online (Sandbox Code Playgroud) 我知道Singleton类是一个类,一次只能创建一个对象.
我的问题是:
1. 在objective-c中使用Singleton类有什么用?
2. 如何创建和使用创建的Singleton类?