我有一个nsmutablearray,我从nsarray的for循环中向它添加对象。我希望它添加对象,直到它到达NSArray的indexOfObject:中的NSNotFound为止。
该数组位于for循环内,用于从每个索引提取字符串。

我的代码:

NSInteger untilNotFound = NSNotFound;
NSUInteger index = [array indexOfObject:string];

for (index; index < untilNotFound; index ++)
{
    [self.mutablearray addObject:[array objectAtIndex: index]];
}

编辑:
for (string in array)
{
NSComparisonResult *result = [string compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)
                              range:NSMakeRange(0, [searchText length])];

if (result == NSOrderedSame)
{
            NSInteger index;
            for (index =[array indexOfObject:string]; (index < [array count] && index < 100 && index!= NSNotFound); index ++)
            {
                [self.mutablearray addObject:[array objectAtIndex: index]];

            }

break;

}

}

编辑。

我以前的代码有效,它位于if(result == NSOrderedSame)内部,我只是想知道是否有任何更好,更轻松且性能友好的解决方案在索引到达NSNotFound之前就可以提取它:
        NSUInteger new = [array indexOfObject:string];

        NSString *last = [array lastObject];

        NSUInteger total = [array indexOfObject:last];

        NSUInteger newmax = new + 10;

        NSUInteger totalminus = total - 11;


        if (newmax <= totalminus )

        {

            [self.mutablearray addObject:string];

            [self.mutablearray addObject:[array objectAtIndex:new + 1]];

            [self.mutablearray addObject:[array objectAtIndex:new + 2]];
            [self.mutablearray addObject:[array objectAtIndex:new + 3]];
            [self.mutablearray addObject:[array objectAtIndex:new + 4]];
            [self.mutablearray addObject:[array objectAtIndex:new + 5]];
            [self.mutablearray addObject:[array objectAtIndex:new + 6]];
            [self.mutablearray addObject:[array objectAtIndex:new + 7]];
            [self.mutablearray addObject:[array objectAtIndex:new + 8]];
            [self.mutablearray addObject:[array objectAtIndex:new + 9]];
            [self.mutablearray addObject:[array objectAtIndex:new + 10]];
        }

        else
        {
            [self.mutablearray addObject:string];
        }

最佳答案

看来您正在尝试做一个累积子集。试试这个:

for(NSInteger index = [array indexOfObject: string]; ((index <  [array count]) &&
                                                      (index <= 100)           &&
                                                      (index != NSNotFound))   ;  index++)
{
    [self.mutablearray addObject: [array objectAtIndex: index]];
}

或者,如果您只是执行严格的子集,请尝试以下操作:
NSInteger startIndex = [array indexOfObject: string];
NSInteger endIndex = MIN([array count], 100);
if(startIndex != NSNotFound)
{
    self.mutablearray = [array subarrayWithRange: NSMakeRange(startIndex, endIndex)] mutableCopy];
}

10-08 05:04