
>发出网络请求
>显示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]; 注意,我也使用了睡眠,但确保这些是在后台线程中执行以模拟网络调用.日志内容如下
1...12...2
这是所希望的.这种方法有什么问题?有什么警告我应该知道吗?
解决方法 乍一看,这可行,但有些部分缺少一个“适当的”NSOperation子类.你没有应对’已取消’状态,你应该在开始时检查isCancelled,如果返回YES则不启动(“responding to the cancel command”)
并且isConcurrent方法也需要被覆盖,但为简洁起见,您可能省略了它.
总结以上是内存溢出为你收集整理的ios – 在目标C中序列化异步任务全部内容,希望文章能够帮你解决ios – 在目标C中序列化异步任务所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)