1

私は配列を持つ配列を持っています ex.: ( ( object, object ), ( object, object, object, object ) )

それぞれobjectにプロパティ.objectIDがあります。特定のオブジェクトを見つける最良の方法はobjectID何ですか?

4

3 に答える 3

3

次の 2 つのオプションがあります。

オプション 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 の実行時間と見なされますが、これらは必要な範囲でのみ実行されます。オブジェクトを見つけると、彼らは検索をやめます。

于 2013-06-07T14:34:33.100 に答える
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

于 2013-06-07T14:03:33.397 に答える
0

順序を気にしない場合は、代わりに objectId がキーである辞書の配列を使用できます。これにより、検索が O(N) になります。

于 2013-06-07T18:26:27.323 に答える