在 NSArray 中搜索多个项目

发布于 2024-12-29 06:26:17 字数 679 浏览 6 评论 0原文

我有一个 NSArray 并且许多值具有相同的值(我知道这不是创建数组的最佳方法)。我如何在数组中搜索字符串并让它返回索引数组。例如,如果我想在数组中搜索“DJ Ez”,我怎样才能得到它,以便它返回索引等于该字符串的所有索引?到目前为止,我已经尝试过:

do {
   isTheObjectThere = [array containsObject: @"DJ Ez"];
    if(isTheObjectThere == true){
        indexOfTheObject = [array indexOfObject: @"DJ Ez"];
        [arrayOfIndexes addObject:[NSNumber numberWithInt:indexOfTheObject]];
        [array removeObjectAtIndex:indexOfTheObject];
        NSLog(@"%@", [indexesForAll objectAtIndex:intCtrl]);
        hasFinished = false;
    }else{
        hasFinished = true;
    }
    intCtrl++;
} while (hasFinished == false);  

但是这不起作用,因为当它删除该项目时,它会弄乱下一次搜索的所有索引。我该怎么办?

I have an NSArray and a lot of the values have the same values (i know this isn't the best way to do an array). How can i search for a string within the array and have it return me an array of indexes. For example if i wanted to search the array for "DJ Ez", how can i have it so it returns all the indexes where the index is equal to that string? So far i have tried this:

do {
   isTheObjectThere = [array containsObject: @"DJ Ez"];
    if(isTheObjectThere == true){
        indexOfTheObject = [array indexOfObject: @"DJ Ez"];
        [arrayOfIndexes addObject:[NSNumber numberWithInt:indexOfTheObject]];
        [array removeObjectAtIndex:indexOfTheObject];
        NSLog(@"%@", [indexesForAll objectAtIndex:intCtrl]);
        hasFinished = false;
    }else{
        hasFinished = true;
    }
    intCtrl++;
} while (hasFinished == false);  

However this doesn't work as when it deletes the item it messes up all the indexes for the next search. What do i do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你又不是我 2025-01-05 06:26:17

怎么样:

NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
    return [obj isEqualToString:@"DJ Ez"];
}];

这应该以 NSIndexSet 的形式返回所有匹配的索引,这允许您检查特定索引是否匹配,或者您可以根据需要获取计数并循环匹配的索引。

How about something like this:

NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
    return [obj isEqualToString:@"DJ Ez"];
}];

That should return all of the matching indexes as an NSIndexSet, which allows you do check if specific indexes matched, or you can get the count and loop through the matching indexes however you wish.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文