大佬教程收集整理的这篇文章主要介绍了ios – 在目标C中序列化异步任务,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
>发出网络请求
>显示UIAlertView
这通常是一项棘手的业务,大多数串行队列样本在NSBlockOperation的块中显示“睡眠”.这不起作用,因为只有在回调发生时才完成操作.
我已经通过继承NSOperation实现了这个,这是实现中最有趣的部分:
+ (MYOperation *)operationWithBlock:(CompleteBlock)block { MYOperation *operation = [[MYOperation alloc] init]; operation.block = block; return operation; } - (void)start { [self willChangeValueForKey:@"isExecuTing"]; self.execuTing = YES; [self didChangeValueForKey:@"isExecuTing"]; if (self.block) { self.block(self); } } - (void)finish { [self willChangeValueForKey:@"isExecuTing"]; [self willChangeValueForKey:@"isFinished"]; self.execuTing = NO; self.finished = YES; [self didChangeValueForKey:@"isExecuTing"]; [self didChangeValueForKey:@"isFinished"]; } - (BOOL)isFinished { return self.finished; } - (BOOL) isExecuTing { return self.execuTing; }
这很好用,这是一个示范……
NSOperationQueue *q = [[NSOperationQueue alloc] init]; q.maxConcurrentOperationCount = 1; dispatch_queue_t queue = dispatch_queue_create("1",null); dispatch_queue_t queue2 = dispatch_queue_create("2",null); MYOperation *op = [MYOperation operationWithBlock:^(MYOperation *o) { NSLog(@"1..."); dispatch_async(queue,^{ [NSThread sleepForTimeInterval:2]; NSLog(@"1"); [o finish]; // this signals we're done }); }]; MYOperation *op2 = [MYOperation operationWithBlock:^(MYOperation *o) { NSLog(@"2..."); dispatch_async(queue2,^{ [NSThread sleepForTimeInterval:2]; NSLog(@"2"); [o finish]; // this signals we're done }); }]; [q addoperations:@[op,op2] waitUntilFinished:YES]; [NSThread sleepForTimeInterval:5];
注意,我也使用了睡眠,但确保这些是在@L_489_4@线程中执行以模拟网络调用.日志内容如下
1... 1 2... 2
这是所希望的.这种方法有什么问题?有什么警告我应该知道吗?
你没有应对’已取消’状态,你应该在开始时检查isCancelled,如果返回YES则不启动(“responding to the cancel command”)
并且isConcurrent方法也需要被覆盖,但为简洁起见,您可能省略了它.
以上是大佬教程为你收集整理的ios – 在目标C中序列化异步任务全部内容,希望文章能够帮你解决ios – 在目标C中序列化异步任务所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。