【发布时间】:2014-08-10 15:05:26
【问题描述】:
我正在开发一个数字杂志阅读器应用程序,它需要先下载杂志。 在下载它们时,我想在视图控制器之间传递下载进度数据。 这就是我使用单例设计模式的原因。 我还使用 NSNotification 在下载时更新进度条百分比。但我认为每毫秒发送通知并不是很有效。所以我决定使用委托设计模式,但我不知道要实现自定义的 delagete 方法。对自定义委托有任何帮助吗?它是使用委托的最佳方式吗?
// Header
@interface ZXCSingleton : NSObject
+ (id)sharedInstance;
- (BOOL)isDownloadingProduct:(NSString *)productID;
- (void)addToDownloadListWithProductID:(NSString *)productID;
- (void)removeFromDownloadListWithProductID:(NSString *)productID;
- (NSArray *)getDownloadList;
- (void)setDownloadProgress:(float)progress
withProductID:(NSString *)productID;
- (float)getDownloadProgressWithProductID:(NSString *)productID;
@end
// M
#import "ZXCSingleton.h"
@implementation ZXCSingleton{
NSMutableArray *downloadList;
NSMutableDictionary *downloadProgress;
}
+ (id)sharedInstance
{
static ZXCSingleton *sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
sharedInstance = [[ZXCSingleton alloc] init];
});
return sharedInstance;
}
- (id)init
{
self = [super init];
if (self) {
downloadList = [[NSMutableArray alloc] init];
downloadProgress = [[NSMutableDictionary alloc] init];
}
return self;
}
- (BOOL)isDownloadingProduct:(NSString *)productID
{
for (int i = 0; i < downloadList.count; i++) {
if ([[downloadList objectAtIndex:i] isEqualToString:productID]) return YES;
}
return NO;
}
- (void)addToDownloadListWithProductID:(NSString *)productID
{
[downloadList addObject:productID];
}
- (void)removeFromDownloadListWithProductID:(NSString *)productID
{
[downloadList removeObject:productID];
}
- (NSArray *)getDownloadList
{
return downloadList;
}
- (void)setDownloadProgress:(float)progress
withProductID:(NSString *)productID
{
if (progress != [[downloadProgress objectForKey:productID] floatValue]) [[NSNotificationCenter defaultCenter] postNotificationName:@"downloading" object:nil];
[downloadProgress setObject:[NSString stringWithFormat:@"%0.2f", progress] forKey:productID];
}
- (float)getDownloadProgressWithProductID:(NSString *)productID
{
return [[downloadProgress objectForKey:productID] floatValue];
}
【问题讨论】:
标签: ios objective-c delegates singleton