Objective C - 示例Singleton实现

gui*_*eak 1 singleton objective-c ios

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

我刚刚尝试在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 *)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
Run Code Online (Sandbox Code Playgroud)

在这里调用getInstance时:

PeopleDatabase *database = [PeopleDatabase getInstance];
NSLog(@"Adress 2: %p", database);
Run Code Online (Sandbox Code Playgroud)

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

Fog*_*ter 25

创建单例的标准方法就像......

Singleton.h

@interface MySingleton : NSObject

+ (MySingleton*)sharedInstance;

@end
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)