我有数组,例如:((对象,对象),(对象,对象,对象,对象))
每个object
都有属性.objectID
。找到特定对象的最佳方法是objectID
什么?
我有数组,例如:((对象,对象),(对象,对象,对象,对象))
每个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)。