ios - objective-c -单例实现示例

标签 ios objective-c singleton

*我肯定需要休息一下...原因很简单-未分配数组...感谢您的帮助。由于这个尴尬的错误,我标记了我的帖子以将其删除。我认为这对用户没有帮助;)*

我刚刚尝试在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/

相关文章:

ios - iOS 6 是否支持 OpenSSL?

java - SQLite Handler 类作为单例?

ThreadStatic 的 C# 单例模式设计

c++ - 是否有开源音频流客户端或框架?

java - 为每个类使用单个 JAXBContext 还是单独的上下文更好?

ios - 如何在 Sinch 中设置 App-to-App 调用相互发起?

ios - 重新运行应用程序后在 UIDatePicker 中显示保存的时间

ios - 如何在arduino上实现外设上的代码

ios - 获取日期格式 | swift | iOS系统

ios - 标准显示转场动画