NPDispatcher 1.0.1

NPDispatcher 1.0.1

测试测试
语言语言 Obj-CObjective C
许可证 MIT
发布日期最后发布2017年6月

zhang33121维护。



  • zhang.wenhai

NPDispatcher是一个适用于iOS和Mac OS X的任务调度库,它可以限制同时运行的任务的最大数量。

选择NPDispatcher作为您的下一个项目的工具,您会为这个决定感到高兴!

示例项目

要运行示例项目,首先克隆仓库,然后从示例目录中运行 pod install

要求

NPDispatcher版本 最低iOS目标 最低OS X目标 最低watchOS目标 最低tvOS目标 注意
1.x iOS 8 OS X 10.9 watchOS 2.0 tvOS 9.0 需要使用Xcode 7+。

Podfile

要使用CocoaPods将NPDispatcher集成到您的Xcode项目中,请在您的Podfile中指定它

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'

target 'TargetName' do
pod 'NPDispatcher', '~> 1.0.0'
end

然后,运行以下命令

$ pod install

使用方法

NPTask

NPTask是任务的载体,通过标识符区分不同的任务。使用以下方法创建任务并启动。

+ (id)taskWithIdentifier:(NSUInteger)identifier dataObject:(id)data;
- (id)initWithIdentifier:(NSUInteger)identifier dataObject:(id)data;
- (void)start;

当任务完成时,您可以提交(成功)或失败它。

- (void)commit;
- (void)fail:(NSError *)error;

NPDispatcher

NPDispatcher是任务运行和待处理的经理。

      

1. 初始化。设置同时运行的任务的最大数量和新任务派发回调。

+ (NPDispatcher *)dispatcherWithMaxTaskCount:(NSUInteger)maxCount taskArrivedCallBack:(NPTaskArrivedCallBack)callBack;
- (NPDispatcher *)initWithMaxTaskCount:(NSUInteger)maxCount taskArrivedCallBack:(NPTaskArrivedCallBack)callBack;

2. 添加任务。

- (void)addTask:(NPTask *)task;
- (void)addTasks:(NSArray<NPTask *> *)tasks;
- (void)insertTask:(NPTask *)task atIndex:(NSInteger)index; 

3. 任务完成后移除。

- (void)removeTask:(NPTask *)task;

4. 如果不必要执行,取消未启动的任务。

- (NSArray<NPTask *> *)cancelNotStartTasks;

使用示例

1. 定义

@property (nonatomic, strong) NPDispatcher *dispatcher;

2. 初始化

__weak typeof(self)weakSelf = self;
_dispatcher = [NPDispatcher dispatcherWithMaxTaskCount:5 taskArrivedCallBack:^(NSArray<NPTask *> *tasks) {
    NSUInteger taskCount = tasks.count;
    for (NSUInteger index = 0; index < taskCount; index ++) {
        NPTask *task = [tasks firstObject];
        //If Success
        [task commit];
        //If Fail
        [task fail:[NSError errorWithDomain:@"NPDispatcher" code:-1 userInfo:@{@"error" : @"I`m uncareful failed."}]];
    }
}];

3. 添加任务

NSMutableArray<NPTask *> *testTasks = [NSMutableArray arrayWithCapacity:10];
for (int index = 0; index < 10; index ++) {
    //1. Create task
    NPTask *task = [NPTask taskWithIdentifier:index dataObject:nil];
    //2. Start task
    [task start];
    //3. Set success call back
    task.successCallBack = ^(NPTask *t) {
        NSLog(@"task %lu success.", t.identifier);
        //6. Remove complete task from dispatcher
        [weakSelf.dispatcher removeTask:t];
    };
    //4. Set failed call back
    task.failedCallBack = ^(NPTask *t, NSError *error) {
        NSLog(@"task %lu failed:%@.", t.identifier, t.error.description);
        //6. Remove complete task from dispatcher
        [weakSelf.dispatcher removeTask:t];
    };
    [testTasks addObject:task];
}
//5. Add tasks
[_dispatcher addTasks:testTasks];

作者

张文海,[email protected]

许可证

NPDispatcher可在MIT许可证下获得。有关更多信息,请参阅LICENSE文件。