objective-c - 如何在 Objective-C 中执行回调

如何在 Objective-C 中执行回调函数?

我只是想看看一些完整的例子,我应该理解它。

最佳答案

为了完整起见,由于 StackOverflow RSS 只是随机地为我复活了这个问题,另一个(较新的)选项是使用 block :

@interface MyClass: NSObject
{
    void (^_completionHandler)(int someParameter);
}

- (void) doSomethingWithCompletionHandler:(void(^)(int))handler;
@end


@implementation MyClass

- (void) doSomethingWithCompletionHandler:(void(^)(int))handler
{
    // NOTE: copying is very important if you'll call the callback asynchronously,
    // even with garbage collection!
    _completionHandler = [handler copy];

    // Do stuff, possibly asynchronously...
    int result = 5 + 3;

    // Call completion handler.
    _completionHandler(result);

    // Clean up.
    [_completionHandler release];
    _completionHandler = nil;
}

@end

...

MyClass *foo = [[MyClass alloc] init];
int x = 2;
[foo doSomethingWithCompletionHandler:^(int result){
    // Prints 10
    NSLog(@"%i", x + result);
}];

https://stackoverflow.com/questions/1015608/

相关文章:

objective-c - NSLog 覆盖描述方法中对象的内存地址

objective-c - 允许与另一个 UIView 下的 UIView 交互

objective-c - "Auto Layout still required after ex

iphone - cocoa 应用程序的 info plist 中的 "bundle display

iphone - 如何在 UITableView beginUpdates/endUpdates 上

iphone - 如何使 UIView 的 subview 居中

ios - UIActionSheet 取消按钮的奇怪行为

ios - 以编程方式获取导航栏的高度

objective-c - 检查当前线程是否是主线程

objective-c - 取消排队的 performSelector :afterDelay ca