我和我的单身人士走在正确的轨道上吗?

时间:2013-07-29 03:40:55

标签: iphone ios objective-c singleton nstimer

昨天我问了一个关于我的表视图的问题,并将唯一的详细视图链接到表视图中的每个单元格。我相信我的问题得到了很好的回答here。 (希望你能阅读那篇文章,看看我需要什么)。基本上我想知道我是否正确制作单身。这是我的代码:

timerStore.h

#import "Tasks.h"
@interface timerStore : NSObject
{
    NSMutableDictionary *allItems;
}
+(timerStore *)sharedStore;
-(NSDictionary *)allItems;
-(NSTimer *)createTimerFor:(Tasks *)t inLocation: (NSIndexPath *)indexPath;
-(void)timerAction;
@end

timerStore.m

@implementation timerStore

+(timerStore *)sharedStore{
    static timerStore *sharedStore = nil;
    if (!sharedStore)
        sharedStore = [[super allocWithZone:nil]init];
    return sharedStore;
}
+(id)allocWithZone:(NSZone *)zone{
    return [self sharedStore];
}
-(id)init {
    self = [super init];
    if (self) {
        allItems = [[NSMutableDictionary alloc]init];
    }
    return self;
}
-(NSDictionary *)allItems{
    return allItems;
}
-(NSTimer *)createTimerFor:(Tasks *)t inLocation: (NSIndexPath *)indexPath {
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:t.timeInterval target:self selector:@selector(timerAction) userInfo:nil repeats:1.0];
    [allItems setObject:timer forKey:indexPath];
    return timer;
}
-(void)timerAction{
//custom properties here
}
@end

我有点困惑,因为我的印象是当你向下滚动(出列)时,单元格的索引路径会被回收。我可能错了。无论如何,我是否正在建立link建议的单身人士的正确道路?

1 个答案:

答案 0 :(得分:2)

实施App Singleton的最佳方法如下

标头文件

#import <Foundation/Foundation.h>

@interface AppSingleton : NSObject

@property (nonatomic, retain) NSString *username;

+ (AppSingleton *)sharedInstance;

@end

实施档案

#import "AppSingleton.h"

@implementation AppSingleton
@synthesize username;

+ (AppSingleton *)sharedInstance {
    static AppSingleton *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

// Initializing
- (id)init {
    if (self = [super init]) {
        username = [[NSString alloc] init];
    }
    return self;
}

@end

注意: 这样做的是它定义了一个名为sharedInstance的静态变量(但只有translation unit的全局变量),然后在sharedInstance方法中初始化一次 。我们确保仅创建一次的方式是使用Grand Central Dispatch (GCD)中的dispatch_once method。这是线程安全的,完全由操作系统为您处理,因此您根本不必担心它。

使用Singleton设置值

[[AppSingleton sharedInstance] setUsername:@"codebuster"];

使用Singleton获取价值。

NSString *username = [[AppSingleton sharedInstance] username];

Further Reference and Reading