【问题标题】:Background (Asynchronous) programming in Cocoa/Objective-CCocoa/Objective-C 中的后台(异步)编程
【发布时间】:2014-10-29 18:49:10
【问题描述】:

我想要类似于 C# 的BackgroundWorker

我想在为NSProgressIndicator 制作动画时在后台执行一段代码块(不管它是什么类型的代码。它可能是网络、I/O、复杂的数学运算等等)。操作完成后,我不仅想隐藏进度指示器,还想从后台代码接收结果对象返回到主代码。

最好的方法是什么?

感谢您的帮助!

【问题讨论】:

标签: objective-c multithreading cocoa asynchronous background-process


【解决方案1】:

您可能想要阅读有关NSOperationNSOperationQueueblocks 的信息。

使用这些,您可以异步执行您的“代码块”,并让它每隔一段时间“安排”一次主线程上的进度指示器的更新。您可以设置一个完成块(回调)在操作完成时执行,它可以调用要在主线程上执行的函数。

This article 通过小示例很好地概述了选项。

This answer 提供了定义和使用完成块的示例。

【讨论】:

    【解决方案2】:

    我认为这个库会有所帮助 - https://github.com/AFNetworking/AFNetworking

    此库是 Apple API 的包装器,并且可以正确处理异步任务。该示例由 Matt Thompson 在这里展示 How to download a file and save it to the documents directory with AFNetworking? 如何在后台使用 API 从 url 下载资源。这只是一个示例,但它们中的大多数都以类似的方式在后台执行任务而不阻塞主 UI 线程

    例如:-

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"..."]];
    AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:@"filename"];
    operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Successfully downloaded file to %@", path);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
    [operation start];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-24
      • 2013-03-25
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多