@blog.justoneplanet.info

日々勉強

Objective-CでSingleton

■実装

#import <Foundation/Foundation.h>

@interface TapManager : NSObject {
}
+ (id)instance;
+ (id)allocWithZone:(NSZone *)zone;
- (id)copyWithZone:(NSZone *)zone;
- (id)retain;
- (unsigned)retainCount;
- (void)release;
- (id)autorelease;
- (void)registerWithFace:(NSString *)face withTag:(NSString *)tag;
@end
#import "TapManager.h"
#import "HistoryDB.h"
#import "Util.h"

@implementation TapManager
static TapManager *_instance = nil;

+ (TapManager *)instance {
    @synchronized(self) {
        if (_instance == nil) {
            [[self alloc] init];//代入はしない
        }
    }
    return _instance;
}

// zoneからオブジェクトを生成する
+ (id)allocWithZone:(NSZone *)zone {
    @synchronized(self) {
        if (_instance == nil) {
            _instance = [super allocWithZone:zone];// 最初のみ代入する
            return _instance;// 最初のみ値を返す
        }
    }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone {
    return self;
}

- (id)retain {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;
}

- (void)release {
}

- (id)autorelease {
    return self;
}

- (void)registerWithFace:(NSString *)face withTag:(NSString *)tag {
    UIPasteboard *pb = [UIPasteboard generalPasteboard];
    [pb setValue:face forPasteboardType:@"public.utf8-plain-text"];
    [Util showAlert:@"Hello" text:@"World"];
    // ...その他の処理
}
@end

コメントはまだありません»

No comments yet.

RSS feed for comments on this post.TrackBack URL

Leave a comment