Am I on the right track with my singleton?
我昨天问了一个关于我的表视图的问题,并将独特的细节视图链接到表视图中的每个单元格。我相信我的问题得到了很好的答案。(希望你能读到那篇文章,看看我需要什么)。基本上我想知道我是不是在做我的单身汉。这是我的代码:
TimeStury.h
1 2 3 4 5 6 7 8 9 10 | #import"Tasks.h" @interface timerStore : NSObject { NSMutableDictionary *allItems; } +(timerStore *)sharedStore; -(NSDictionary *)allItems; -(NSTimer *)createTimerFor:(Tasks *)t inLocation: (NSIndexPath *)indexPath; -(void)timerAction; @end |
TimeStur.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | @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 |
我有点困惑,因为我觉得当向下滚动(dequeue)时,单元格的索引路径会被循环使用。不过,我可能错了。不管怎么说,我是不是按照链接中的人的建议做一个单身汉?
实现app singleton的最佳方法如下
头文件
1 2 3 4 5 6 7 8 9 | #import <Foundation/Foundation.h> @interface AppSingleton : NSObject @property (nonatomic, retain) NSString *username; + (AppSingleton *)sharedInstance; @end |
实施文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #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 |
注:它所做的是定义一个称为
使用singleton设置值
1 | [[AppSingleton sharedInstance] setUsername:@"codebuster"]; |
使用singleton获取值。
1 | NSString *username = [[AppSingleton sharedInstance] username]; |
进一步参考和阅读