如何使用NSOperation& Objective-C中的NSOperationQueue?

时间:2016-10-10 06:57:27

标签: objective-c nsoperation nsoperationqueue

我正在开发一个自定义相机应用程序。我正在做的是,我正在使用相机拍照并将它们显示在屏幕的同一个VC底部。

我将图像存储在本地词典和NSDocument目录路径中。如果图片在本地词典中,它将从本地字典中获取,它将从NSDocument目录路径中获取。

收到内存警告后,我只是字典,所以它将从NSDocument目录路径中获取图像。

使用两者都会在缓慢的过程中显示图像。我的UI在显示图像时没那么好。

所以我想使用NSOperation将图像存储在NSDocument目录路径中。

我对NSOperation不太了解。我在谷歌搜索过,我只需要快速的教程,而我需要Objective C中的帮助。

所以,任何人都可以通过示例解释NSOperationNSOperationQueue吗?

2 个答案:

答案 0 :(得分:6)

为每项工作申请:

        // Allocated here for succinctness.
        NSOperationQueue *q = [[NSOperationQueue alloc] init];

        /* Data to process */
        NSData *data = [@"Hello, I'm a Block!" dataUsingEncoding: NSUTF8StringEncoding];

        /* Push an expensive computation to the operation queue, and then
         * display the response to the user on the main thread. */
        [q addOperationWithBlock: ^{
            /* Perform expensive processing with data on our background thread */
            NSString *string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];



            /* Inform the user of the result on the main thread, where it's safe to play with the UI. */

            /* We don't need to hold a string reference anymore */

        }];

你也可以在没有NSOperationQueue的情况下申请:

       dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Your Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update your UI


            });
        });

再试一次:

  1. NSOperationQueue addOperationWithBlock return to mainQueue order of operations

  2. http://landonf.org/code/iphone/Using_Blocks_1.20090704.html

  3. https://videos.raywenderlich.com/courses/introducing-concurrency/lessons/7

答案 1 :(得分:1)

Swift3 创建一个操作队列

lazy var imgSaveQueue: OperationQueue = {
    var queue = OperationQueue()
    queue.name = "Image Save Queue"
    queue.maxConcurrentOperationCount = 1
    return queue
}()

向其添加操作

imgSaveQueue.addOperation(BlockOperation(block: { 
       //your image saving code here 
    }))

对于目标C:

[[NSOperationQueue new] addOperationWithBlock:^{ 

      //code here 

}];