代码之家  ›  专栏  ›  技术社区  ›  Rudiger

调用nsOperationQueue和dealloc时出现问题,应用程序崩溃

  •  1
  • Rudiger  · 技术社区  · 15 年前

    我在队列中创建了一个nsoperation,如下所示:

    ImageLoadingOperation *operation = [[ImageLoadingOperation alloc] initWithImageURL:url target:self action:@selector(didFinishLoadingImageWithResult:)];
    [operationQueue addOperation:operation];
    [operation release];
    

    这很好,但如果在操作完成前弹出视图,应用程序将崩溃,并出现“exc-bad-u访问”

    我试图通过调用cancelalloperations来取消操作队列,但由于它已经在处理中,所以它不能防止应用程序崩溃。docos说,如果操作正在运行,则由操作来检测它是否已被取消,并做出适当的响应,但不太确定我将如何实现这一点?

    有什么想法吗?

    3 回复  |  直到 10 年前
        1
  •  1
  •   vodkhang    15 年前

    视图调用某个网络然后回调是一个普遍的问题。

    我的解决方案是在调用操作之前可以保留视图。然后,当操作完成时,释放视图。

    - (void)longTask {
       [self retain];
    }
    
    - (void)longTaskDidFinish {
       // do something if you want
       [self release];
    }
    
        2
  •  0
  •   Motti Shneor    10 年前

    您必须重写ImageLoadingOperation类中的“Cancel”操作,或者将ImageLoadingOperation本身作为kvo观察器添加到“Cancelled”属性中。在那里-你可以智能地取消你的操作,这样它不会崩溃。

    此外,如果您的ImageLoadingOperation在后台运行,那么以某种方式将您对视图的访问推迟到主线程(在主线程中进行所有绘图)会更明智。您可以使用Dispatch_Sync(Dispatch_Get_Main_Queue(),^)或甚至PerformSelectorOnManInThread来实际访问相关视图。

    您看到了-使用操作队列的整个要点是删除依赖项,并让事情并行运行,但是您的操作必须与视图系统更改同步,并且必须为完整性和健壮性而设计。

        3
  •  0
  •   Mindy    10 年前

    您可以在调用操作回调之前保留该视图,如上面提到的vodkhang。但这将不必要地延长视图的使用寿命,因为视图被弹出后,您不希望操作继续进行。
    下面是一个关于如何响应取消命令的草图:

    - (void)start{
        if(self.isCancelled){
           [self markAsFinished];
           return;
        }
        //start your task asynchronously
    }
    
    
    //If you want to cancel the downloading progress immediately, implement your own 'cancel' method
    - (void)cancel{
        [super cancel];
        if(self.isExecuting){
           {
              ......
              cancel load process
              ......
           }
           [self markAsFinished];
        }
    }
    
    - (void)markAsFinished{
        ......
        change 'finished' to YES'  generate KVO notifications on this key path
        change 'executing' to 'YES'; generate KVO notification on this key path
        ...... 
    }
    

    此草图基于AsihttpRequest网络库,并且 有一个 official guide 关于如何响应取消命令。

    推荐文章