2013-07-29 91 views
1

昨天我问了一个关于我的表视图的问题,并将唯一的细节视图链接到表视图中的每个单元格。我相信我对我的问题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建议的人?

+0

你知道,我一直在编程,现在4年iOS的 - 在工作半打不同的大型应用。我还没有需要使用单身。 –

+1

特别是,如果你有一个表格视图,你必须有一个视图控制器。该视图控制器可以包含表格的数据(作为委托)。单身人士不需要存储表格数据。 –

+0

是的,我想避免使用单身人士,但我不知道如何做到这一点。基本上即时使用NSFetchedResultsController填充表视图(链接到UIViewController子类)。每个单元格应在其详细视图中有一个计时器(由didSelectRowAtIndexPath产生)。显然单身是确保多个计时器可以共存并通过将详细视图限制为一个初始化来减少内存使用的最佳方式......更多信息请参阅OP – EvilAegis

回答

2

实现应用辛格尔顿是如下

头文件

#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。这是线程安全的,完全由操作系统为您处理,因此您不必担心它。

使用辛格尔顿设定值

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

使用辛格尔顿拿到价值。

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

Further Reference and Reading

+0

你为什么不指通过OP [此页](http://www.galloway.me.uk/tutorials/singleton-classes/)呢?顺便说一下,你*阅读*的问题呢? –

+1

@KhanhNguyen我曾经参考过链接,但大部分都是因为这个而被低估。 :) – icodebuster

+0

感谢告诉我如何使一个单身人士,但我更感兴趣,如果我是在正确的轨道上的链接中的人(在原来的职位)建议 – EvilAegis