1

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

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

我有点困惑,因为我的印象是,当您向下滚动(出列)时,单元格的索引路径会被回收。不过我可能是错的。无论如何,我是否按照链接中的建议制作单身人士的正确道路?

4

1 回答 1

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,然后在Method中初始化一次且仅一次。sharedInstance我们确保它只创建一次的方法是使用dispatch_once method来自Grand Central Dispatch (GCD)。这是线程安全的,完全由操作系统为您处理,因此您完全不必担心。

使用 Singleton 设置值

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

使用 Singleton 获取价值。

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

进一步参考和阅读

于 2013-07-29T04:32:27.233 回答