Objective C - 示例Singleton实现 [英] Objective C - sample Singleton implementation

查看:80
本文介绍了Objective C - 示例Singleton实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我刚尝试在iOS中创建一个单例类,但我可能犯了一个错误。代码(无需ARC):

I have just tried to create a singleton class in iOS, but I probably I am making a mistake. Code (no ARC is a requirement):

#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时:

When invoking getInstance like here:

PeopleDatabase *database = [PeopleDatabase getInstance];
NSLog(@"Adress 2: %p", database);

地址2的值与getInstance中的值相同。

Address 2 value the same value as in getInstance.

推荐答案

创建单例的标准方法如... ...

The standard way of creating a singleton is like...

Singleton.h

Singleton.h

@interface MySingleton : NSObject

+ (MySingleton*)sharedInstance;

@end

Singleton.m

Singleton.m

#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

这篇关于Objective C - 示例Singleton实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆