在Array中查找对象的最佳方法

时间:2013-06-07 14:01:02

标签: ios objective-c find nsarray

我有阵列数组: (  (   宾语,   宾语  )  (   宾语,   宾语,   宾语,   宾语  ) )

每个object都有.objectID属性。找到具有特定objectID的对象的最佳方式是什么?

3 个答案:

答案 0 :(得分:3)

以下是两个选项:

选项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执行时间,但这些只会在他们需要的时候运行。一旦找到对象,他们就会停止搜索。

答案 1 :(得分: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

答案 2 :(得分:0)

如果您不关心订单,您可以改为使用一个字典数组,其中objectId是关键字。这使你的搜索O(N)。