gpt4 book ai didi

ios - NSOperationQueue 在完成任务之前获得完成通知

转载 作者:行者123 更新时间:2023-11-29 12:29:26 28 4
gpt4 key购买 nike

我在我的应用程序中使用了 NSOperation 子类,它将在单个操作中执行以下 4 个任务,我希望所有这 4 个任务都在后台线程上运行,所以我将其封装到单个 NSOperation 类,这样我就可以轻松地暂停或取消它

任务

  1. 长时间运行计算
  2. 从核心数据中获取数据
  3. 更新到服务器
  4. 更新核心数据

这里每个都必须同步执行,这意味着除了长时间运行的计算之外,每个都依赖于另一个。

代码

// MyOperation.h
@interface MyOperation : NSOperation {
}
@property (nonatomic, getter = isCancelled) BOOL cancelled;
@end

// MyOperation.m
@implementation MyOperation

- (void)cancel
{
@synchronized (self)
{
if (!self.cancelled)
{
[self willChangeValueForKey:@"isCancelled"];
self.cancelled = YES;
[webServiceOperation cancel]
[self didChangeValueForKey:@"isCancelled"];
}
}
}

- (void)main {
if ([self isCancelled]) {
NSLog(@"** operation cancelled **");
return;
}
@autoreleasepool{
[self performTasks];
}
}
- (void)performTasks {

[self calculate:^{

if (self.isCancelled)
return;

[self fetchDataFromCoredata:^{

if (self.isCancelled)
return;

//I am using AFNetWorking for updateWebService task so it shall run on separate NSOperation so it would be like nested NSOPeration

webServiceOperation = [self updateWebService:^{

if (self.isCancelled)
return;

[self updateCoreData:^{

if (self.isCancelled)
return;
}];
}];
}];


}];

}
@end

我假设我没有遵循正确的方法,因为当我使用 KVO 测试这段代码时,NSOperationQueue 在它到达计算的完成 block 之前得到完整的通知。

问题

  1. 我的方法对吗?
  2. 如果没有,能否指导我正确的方法?
  3. 如果这是正确的方法,那么为什么 NSOPerationQueue 在完成 block 执行之前得到完成通知?

提前致谢!期待您的回复

最佳答案

只是实际上网络调用需要显式异步,因为您的操作已经在后台线程上运行。因此,您可以简化代码中的 block 结构,从而避免太多嵌套。

然后您需要正确构造您的操作子类来处理异步内容,如所述here .

关于ios - NSOperationQueue 在完成任务之前获得完成通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28146296/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com