2016-03-30 35 views
2

我有一個NSMutableOrderedSet。如何返回enumerateObjectsUsingBlock找到的項目?

我需要枚舉它,它看起來像集合上唯一的選項是基於塊。因此,採摘最簡單的基於塊的選擇,我有這樣的事情......

[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?   
    } 
}] 

回答

2

您需要在通話的碼回/塊調出通過。

- (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]; 

UPDATE:

實現enumerateObjectsUsingBlock:實際上是所謂的同步,所以更好的方法是使用一個__block變量。回調仍然有效,但可能被認爲是誤導性的。

+0

難道也有可能在塊外使用'__block SomeClass * someClassVar',然後在塊內部執行'someClassVar = obj'來將結果對象分配給塊外的塊變量?我還沒有嘗試過,但如果我正確理解__block關鍵字,似乎會工作 –

+0

@Logicsaurus雷克斯是的,這將工作。有關__block關鍵字的更多信息,請查看此鏈接:http://stackoverflow.com/questions/7080927/what-does-the-block-keyword-mean –

+0

是的,塊變量也可以。但使用這種方法時要注意範圍。我發現使用明確的回調更具可讀性,但它取決於您,以及它如何適用於您的實現。祝你好運。 – Tim

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); 
-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 
+0

這沒有意義,是一個可怕的想法。你在'anNSMutableOrderedSet'中混合了'self'類型和對象的類型。在大多數情況下,這些類型不會相同。 –

1

在這種情況下,最簡單的事情是不使用enumerateObjectsUsingBlock:,並且只使用快速列舉代替:

for (SomeClass *obj in anNSMutableOrderedSet) { 
    if ([obj isWhatIWant]) { 
     yourVariable = obj; 
     break; 
    } 
}