2

在我的应用程序中,我的主文件创建了一个类的新实例,然后使用 NSOperationQueue 在后台运行类函数,如下所示:

NSOperationQueue backgroundQueue = [NSOperationQueue new];
MyClass mc = [MyClass alloc];
NSInvocationOperation* operation = [[NSInvocationOperation alloc] initWithTarget:mc selector:@selector(runEvents) object:nil];
[backgroundQueue addOperation:operation];

MyClass 然后在 RunEvents 中做一些事情,但我很难将数据传递给 UI。我只是想更新故事板上的标签,我可以在调用 MyClass 的主类中执行此操作,但是如何从 MyClass 更新它?

4

1 回答 1

2

典型的答案是将您的类创建为NSOperation子类并为其提供自定义完成块。如果您的目标是更新完成块中的 UI 或某些模型对象,请确保将该块分派回主队列:

//  CustomOperation.h

#import <Foundation/Foundation.h>

typedef void(^CustomOperationCompletion)(NSString *string);

@interface CustomOperation : NSOperation

@property (nonatomic, copy) CustomOperationCompletion customOperationCompletion;

- (id)initWithCustomCompletion:(CustomOperationCompletion)completion;

@end

//  CustomOperation.m

#import "CustomOperation.h"

@implementation CustomOperation

- (id)initWithCustomCompletion:(CustomOperationCompletion)completion {
    self = [super init];
    if (self) {
        self.customOperationCompletion = completion;
    }
    return self;
}

- (void)main {
    NSLog(@"%s starting", __FUNCTION__);

    sleep(5);

    NSString *string = [[NSDate date] description];

    if (self.customOperationCompletion) {
        [[NSOperationQueue mainQueue] addOperationWithBlock: ^{
            self.customOperationCompletion(string);
        }];
    }

    NSLog(@"%s ending", __FUNCTION__);
}
@end

然后你可以用类似的东西来调用它:

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

CustomOperation *operation = [[CustomOperation alloc] initWithCustomCompletion:^(NSString *string) { 
    // update the UI with the results of the operation; here I'm just going to log it

    NSLog(@"all done, string=%@", string);
}];

[queue addOperation:operation];

显然,更改您的CustomOperationCompletion参数以包含您想要返回的任何内容(我只是传回一个字符串)。

于 2013-10-27T18:52:14.360 回答