在单独的线程上运行代码的最佳方式是什么?是不是:

[NSThread detachNewThreadSelector: @selector(doStuff) toTarget:self withObject:NULL];

或者:

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

我一直在用第二种方法,但我一直在读的韦斯利烹饪书使用了第一种方法.

推荐答案

在我看来,最好的方式是使用libdispatch,也就是Grand Central Dispatch(GCD).它限制你使用iOS4或更高版本,但它非常简单易用.在后台线程上执行一些处理,然后对主Run循环中的结果执行某些操作的代码非常简单和紧凑:

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Add code here to do background processing
    //
    //
    dispatch_async( dispatch_get_main_queue(), ^{
        // Add code here to update the UI/send notifications based on the
        // results of the background processing
    });
});

如果您还没有这样做,请在libdispatch/GCD/blocks上查看WWDC 2010的视频.

Ios相关问答推荐

无法在fastlane和github操作中从react-native 应用程序构建ios

SwiftUI文本编辑器内部滚动填充,无需文本裁剪

如何在SWIFT中处理不可发送的类型?

SwiftUI@Observable不跟踪父类属性中的更改以更新视图

SwiftUI Divider过大了其父视图

在嵌套的DISPATCH_AFTER块中正确使用strong自/弱自

UIControl 子类 - 按下时显示 UIMenu

VStack 显示错误实例方法 'sheet(item:onDismiss:content:)' 要求 'Int' 符合 'Identifiable'

将角半径仅应用于 Swiftui 中按钮的两个角

访问未定义的 stage_in 金属着色器参数

为什么我的应用在 Testflight 中没有下载 dSYM 按钮?

setNeedsLayout 和 setNeedsDisplay

Xcode - 错误 ITMS-90635 - Bundle 包中的 Mach-O 无效 - 提交到 App Store

在 iOS 中获取设备位置(仅限国家/地区)

如何在导航栏右侧添加多个 UIBarButtonItem?

iOS 11 navigationItem.titleView 宽度未设置

获取 iOS 上所有联系人的列表

Xcode 10.2 无法在 iOS < 10 的模拟器上运行应用程序

如何在 Objective-C (iOS) 中的图像上写文本?

使用 xib 创建可重用的 UIView(并从情节提要中加载)