【发布时间】:2013-07-29 03:40:54
【问题描述】:
我昨天问了一个关于我的表格视图以及将独特的详细视图链接到表格视图中的每个单元格的问题。我相信我的问题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 中的人所建议的那样做一个单身人士?
【问题讨论】:
-
你知道,我已经编写 iOS 4 年了——开发过六种不同的大型应用程序。我还不需要使用单例。
-
特别是,如果你有一个表视图,你必须有一个视图控制器。该视图控制器可以包含表的数据(充当委托)。不需要单例来存储表数据。
-
是的,我想避免使用单例,但我不知道该怎么做。基本上我使用 NSFetchedResultsController 来填充表格视图(链接到 UIViewController 子类)。每个单元格的详细视图中都应该有一个计时器(由 didSelectRowAtIndexPath 产生)。显然,单例是确保多个计时器可以共存并通过将详细视图限制为一个初始化来减少内存使用的最佳方式...更多信息在 OP 中的链接
-
与问题无关,但“永远不要以小写开头的类名!!!”
-
我不清楚使用单例是要走的路。即使我对您的另一个问题的回答涉及为选定的每一行创建一个新的详细视图控制器,但这不一定是一件坏事。在使用仪器分析该应用程序时,选择九行仅增加了 1.8 kb 的内存——视图控制器并不是那么重的对象(但这可能取决于您在其中拥有的内容,尤其是图像)。您认为用户会创建多少任务?一些?十?数百?
标签: iphone ios objective-c singleton nstimer