ios NSOperationQueue, operations all run when added and don't queue

守給你的承諾、 提交于 2019-12-06 15:13:31

问题


So, I have a group of ASINetworkQueues that currently run together resulting in a race condition when it comes to DB saves. I am trying to create an NSOperationQueue that will will queue each of these "sub queues". I currently have created an NSOperation with a main method that kicks off the "sub queue" to start it's download.

My problem is that each time I add a sub queue to the main queue using "addOperation" it fires that "main" method straight away so my sub queues run concurrently. I was under the impression the main method was fired one at a time. i.e. only for the operation at the top of the queue.

Maybe i'm missing something here but I can't seem to figure out how to stall the other operations until the first one has finished. Also, I can't even seem to get my program into a situation that results in isReady = 0 for the NSOperation.. that always gives back yes.

here's some code:

NOTE: I have set the NSOperation queue maxConcurrentOperations to 1.

NSOperation Main method:

-(void)main {
    [subQueue download];
}

Setting up the queue:

ChapterDownloadOperation *cdo =  [[ChapterDownloadOperation alloc] init];
cdo.chapter = ch;
[chapterDownloadQueue addOperation:cdo];
[cdo release];

If I add multiple operations the main method fires at the instance it is added to the queue. Is there another function that I should override and use for when that operation is ready to rock. I have a feeling the main method is for setting up the operation.

Any ideas greatly appreciated.

Thanks so much.


回答1:


NSOperationQueue will fire the main method as soon as it can balance that additional processing power.

To limit the queue to one Operation at a time, you could try adding dependencies between each operation before you queue them: [B addDependency:A]; //[B main] will not be called until A has finished executing

Do note however that if A is cancelled, B will still run.

Hope that helps!




回答2:


I have found this example to be very useful http://developer.apple.com/library/ios/#samplecode/ListAdder/Introduction/Intro.html



来源:https://stackoverflow.com/questions/6988307/ios-nsoperationqueue-operations-all-run-when-added-and-dont-queue

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