方法中间的可选块:安全吗?

时间:2012-12-27 04:47:02

标签: objective-c cocoa-touch cocoa objective-c-blocks

我的方法类似于:

- (void)doSomething:(void(^)(MyItem *item))optionalBlock {

    // 1. Do the regular stuff with the item
    item.regularStuff = @"something_regular";

    // 2. Run the optional block
    // which may or may not make some extra modifications to the item
    if (optionalBlock) optionalBlock(item);

    // 3. Save the modified item into the Core Data
    // etc

}

我打算像这样打电话

[self doSomething:nil];

或者:

[self doSomething:^(MyItem *item) {

    // Make some extra modifications to the item before it’s saved
    item.custom = @"custom";

}];

可以安全地假设在第三步我总是得到item已被方法和(可能)可选块修改,或者我是否需要实现某种方式找出该块何时完成执行所以我可以从那里继续?

2 个答案:

答案 0 :(得分:3)

这很安全。您不需要任何特殊检查。

答案 1 :(得分:2)

是和否。

是的,这是安全的,因为如果该块仅包含用于修改item的顺序代码,那么所有这些修改都将在时间控件返回到您的doSomething方法时完成。

但是,如果允许方法的调用者传入任意块,则无法确定它可能做什么以及何时执行。它可以设置定时器,生成线程,使用dispatch_async,或者执行任何其他可能导致它在某种意义上在返回时不会真正“完成”的事情。你在这里交出车钥匙 - 没有什么可以防止打电话的妓女。

实际上,这是超出语言范围的事情,更多的是关于您在API文档中定义的合同类型:如果您希望调用者仅在执行该块期间修改对象,只是告诉他们你期望他们做的事情,不要指望你的API工作。