如何通过enumerateObjectsUsingBlock返回找到的项目?

3

我有一个NSMutableOrderedSet。

我需要枚举它,看起来集合内置的唯一选项是基于块的。因此,选择基于块的最简单选项,我有以下代码...

[anNSMutableOrderedSet enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    if ([(SomeClass*)obj isWhatIWant]) {
        *stop = YES;
        // Ok, found what I'm looking for, but how do I get it out to the rest of the code?        
    }
}]
4个回答

4
您可以使用 __block 在完成块中分配一些值。
__block yourClass *yourVariable;
[anNSMutableOrderedSet enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    if ([(SomeClass*)obj isWhatYouWant]) {
        yourVariable = obj;
        *stop = YES; 
    }
}]

NSLog(@"Your variable value : %@",yourVariable);

3
您需要传递一个回调/代码块以进行调用。
- (void)someMethod
{
    [self enumerateWithCompletion:^(NSObject *aObject) {
        // Do something with result
    }];       
}

- (void)enumerateWithCompletion:(void (^)(NSObject *aObject))completion
{

[anNSMutableOrderedSet enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    if ([(SomeClass*)obj isWhatIWant]) {
        *stop = YES;
        if (completion) {
            completion(obj);
        }
    }
}];
}

你可以使用委托,并调用你已定义的委托来返回对象。
[self.delegate enumerationResultObject:obj];

更新:

注意到 enumerateObjectsUsingBlock: 方法实际上是同步调用的,因此更好的方法是使用一个 __block 变量。回调仍然可以工作,但可能会被误解为有异步操作。


@Logicsaurus Rex,是的,这个可以工作。有关__block关键字的更多信息,请查看此链接:https://dev59.com/YGw05IYBdhLWcg3wsz7N - Raj Tandel
是的,块变量也可以使用。但是在使用此方法时要注意作用域。我发现使用显式回调更易读,但这取决于您的实现方式。祝你好运。 - Tim
@Jeff 你是不是想把枚举代码块放在回调方法里面?那样会不会导致无限循环? - Logicsaurus Rex
我没有定义回调函数,我会加上一个回调函数以便更清晰地解释我的答案。 - Tim
在这种情况下,当它总是同步调用时,不应使用完成处理程序。 - newacct
显示剩余2条评论

1
在这种情况下,最简单的方法是不使用enumerateObjectsUsingBlock:,而是改用快速枚举。
for (SomeClass *obj in anNSMutableOrderedSet) {
    if ([obj isWhatIWant]) {
        yourVariable = obj;
        break;
    }
}

-1

尝试使用 Weak Self

    __weak SomeClass *weakSelf = self;
    [anNSMutableOrderedSet enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([(SomeClass*)obj isWhatIWant]) {
            weakSelf = (SomeClass*)obj;
            *stop = YES;
            // Ok, found what I'm looking for, but how do I get it out to the rest of the code?
        }
    }];

//you Have to use weakSelf outside the block

这没有意义,也是一个糟糕的想法。你混淆了 self 的类型和 anNSMutableOrderedSet 中对象的类型。在大多数情况下,这些类型不会相同。 - Kurt Revis

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接