如何向我的单例添加自定义委托方法

时间:2014-08-10 15:05:26

标签: ios objective-c delegates singleton

我正在开发一个数字杂志阅读器应用程序,它需要先下载杂志。 在下载它们时,我想在viewcontrollers之间传递下载进度数据。 这就是我使用单身设计模式的原因。 我还使用NSNotification在下载时更新progressBar百分比。但我不认为在每一毫秒发送通知是非常有效的。所以我决定使用委托设计模式,但我不知道实现自定义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];
}

1 个答案:

答案 0 :(得分:0)

通过首先创建协议来定义委托,以定义委托所需的接口:

@protocol ZXCSingletonProtocol 

   - (void)downloadProgessUpdates:(float)progress;

@end

在单身人士中为委托创建一个属性:

@property (nonatomic, weak) id<ZXCSingletonProtocol> delegate; 

让您的视图控制器符合该协议:

@interface MyViewController : UIViewController <ZXCSingletonProtocol>

并根据需要在视图控制器中实现downloadProgessUpdates(例如,使用给定的进度号更新UI元素)。请记住在初始化视图控制器时设置委托(viewDidLoad会这样做):

[ZXCSingleton sharedInstance].delegate = self; // self is the view controller instance

在您的单例更新中,setDownloadProgress方法也可以更新代理:

[_delegate downloadProgessUpdates:progress];