线程,优先级和放弃

Fat*_*tie 1 iphone cocoa ios

我最近对iOS很好奇.请指出我将采取的方向,在现代iOS设备上实现(如果可能)以下内容...谢谢!

用户输入文字,每隔几秒钟说一个单词.

有时我想启动DifficultProcess进行一些语义处理.简而言之,我想我需要做四件事:

  • 从main发起DifficultProcess
  • 如果DifficultProcess完成,请将消息从它返回到同一个main
  • 如果我愿意,放弃,摆脱,困难过程,从主要
  • 最后是优先级问题:DifficultProcess必须具有比主要或用户输入低得多的优先级,我希望DifficultProcess真正具有优先级; 甚至可能吗?

基本上,现代(2011年)(1月下旬)iOS中用于A,B,C的调用是什么?我不关心爸爸的方法!并且"D"甚至可能以任何方式?

我猜这些是四个想法!

因此,特别是我想发送一条消息,换句话说,在运行后台进程中调用一个例程(这样,如果需要,可以杀掉正在运行的后台进程,或者可能改变它的操作模式等).

(对于1997年以前出生的人,你会认为这是典型的"投机处理"范式.)

感谢能够为此烦恼的任何人的指点!

Bil*_*son 7

我建议使用NSOperation和NSOperationQueue来管理您需要能够任意取消的后台活动.

NSOperation的-cancel和NSOperationQueue的-cancelAllOperations是要查看的方法.

要将消息从后台返回到主线程,dispatch_async-to-main-thread-queue技术很好.您可以将此与您的NSOperation的委托协议相结合,以编码您要发回的邮件.

例如

@protocol MyOperationDelegate
- (void) operationStarted:(MyOperation *)operation;
- (void) makingProgressOnItem:(id)anItem otherInterestingItem:(NSDictionary *)otherItem remainingCount:(NSUInteger)count;
- (void) operationWillFinish:(MyOperation *)operation;
@end

@interface MyOperation
id <MyOperationDelegate> delegate;
@end

@implementation MyOperation
...

- (void) cancel
{ 
    [super cancel];

    // Tell the delegate we're about to finish (due to cancellation).
    dispatch_sync (dispatch_get_main_queue(), ^{
      [self.delegate operationWillFinish:self];
    });
}

- (void) main 
{
    // Check for cancellation

    if (self.isCancelled) return;

    // Starting

    dispatch_sync (dispatch_get_main_queue(), ^{
        [self.delegate operationStarted:self];
    });

    if (self.isCancelled) return; // Another cancel check


    // Send async progress messages periodically while doing some work

    while (workNotDone) 
    {
        // Do some work ...

        dispatch_async (dispatch_get_main_queue(), ^{
           [self.delegate makingProgressOnItem:foo otherInterestingItem:bar remainingCount:baz];
        });

       if (self.isCancelled) return;
    }


    // About to finish

    if (!self.isCancelled) {
        dispatch_sync (dispatch_get_main_queue(), ^{
           [self.delegate operationWillFinish:self];
        });
    }
}
@end
Run Code Online (Sandbox Code Playgroud)

KVO对于非线性交流并不好; 在发起键值变化的线程上收到观察结果.因此,如果您的后台线程更改了某个值,您的后台线程将收到有关它的KVO.可能不是你想要的.

爷爷的-performSelectorOnMainThread:withObject:waitUntilDone:继续是将消息传回主线程的好方法.限制是您的消息只能访问一个基于对象的参数.主线程的dispatch_async没有此限制.

如果要从后台线程到主线程触发异步(或同步)NSNotification,则需要使用-performSelectorOnMainThread.

NSNotification *note = [NSNotification notificationWithName:FinishedABunchOfWorkNotification object:self userInfo:nil];
[[NSNotificationCenter defaultCenter] performSelectorOnMainThread:@selector(postNotification:) withObject:note waitUntilDone:YES];
Run Code Online (Sandbox Code Playgroud)