[英]Best way to find object in Array
我有帶有數組ex .:((object,object),(object,object,object,object))的數組
每個object
都有.objectID
屬性。查找具有特定objectID
對象的最佳方法是什么?
這里有兩個選項供您選擇:
選項1:使用嵌套的for循環
CustomObject *searchingObject;
// searching through the first array (which has arrays inside of it)
// Note: this will stop looping if it searched through all the objects or if it found the object it was looking for
for (int i = 0; i < [firstArray count] && searchingObject; i++) {
// accessing the custom objects inside the nested arrays
for (CustomObject *co in firstArray[i]) {
if ([co.objectId == 9235) {
// you found your object
searchingObject = co; // or do whatever you wanted to do.
// kill the inside for-loop the outside one will be killed when it evaluates your 'searchingObject'
break;
}
}
}
選項2:使用塊:
// you need __block to write to this object inside the block
__block CustomObject *searchingObject;
// enumerating through the first array (containing arrays)
[firstArray enumerateObjectsUsingBlock:^(NSArray *nestedArray, NSUInteger indx, BOOL *firstStop) {
// enumerating through the nested array
[nestedArray enumerateObjectsUsingBlock:^(CustomObject *co, NSUInteger nestedIndx, BOOL *secondStop) {
if ([co.objectId == 28935) {
searchingObject = co; // or do whatever you wanted to do.
// you found your object now kill both the blocks
*firstStop = *secondStop = YES;
}
}];
}];
盡管仍被認為是N ^ 2執行時間,但它們只會運行所需的時間。 一旦找到對象,便停止搜索。
嘗試一下
[ary filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"objectID == %@", objectID]];
-
id object = nil;
NSPredicate *pred = [NSPredicate predicateWithFormat:@"objectID == %@", objectID];
for(NSArray *subAry in ary)
{
NSArray *result = [subAry filteredArrayUsingPredicate:pred];
if(result && result.count > 0)
{
object = [result objectAtIndex:0];
break;
}
}
因為僵屍關心每個人自己:P
如果您不關心順序,則可以改用字典數組,其中objectId是鍵。 這使您的搜索為O(N)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.