Why is my NSOperationQueue not behaving correctly in iOS 4.0?

独自空忆成欢 提交于 2019-12-23 04:51:17

问题


I have used NSOperationQueue in my iPhone app before in iPhone OS 3.0, but now in iOS 4.0 the code is not working properly. It runs properly only once and on all subsequent calls, it doesnt work. Have there been changes in NSOperationQueue in iOS 4.0?

The relevant code is as follows:

   - (void) starteffectFunction {

        NSOperationQueue *queue = [NSOperationQueue new];
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(starteffectProcessing)
                                                                                  object:nil];

        [queue addOperation:operation];
        [operation release];
        [queue release];
        [spinner startAnimating];
}

    -(void) starteffectProcessing{
    some code executes. code snippet. A 
    ......
    this code is note supposed to execute before A completes. But this executes before A.
    }

回答1:


You are creating an NSOperationQueue, adding an operation to it, then releasing the queue. This is not how NSOperationQueues were designed to work. An NSOperationQueue is supposed to persist, with you adding operations to it as necessary.

This is probably failing because you are deallocating the NSOperationQueue before it has a chance to fire off a thread for your operation. Perhaps on the older OS versions it was just able to do this due to some timing quirk.

I recommend allocating the effect processing queue when you first need it, or in the initialization of your controller object, then keeping that queue around as an instance variable of your controller object. This queue would be deallocated at the same time as your controller object, but you will probably want to cancel all current operations at that time and use NSOperationQueue's –waitUntilAllOperationsAreFinished method to make sure that you are completing all work before deallocation.



来源:https://stackoverflow.com/questions/3987283/why-is-my-nsoperationqueue-not-behaving-correctly-in-ios-4-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!