gpt4 book ai didi

objective-c - NSMutableArray removeObjectAtIndex 用法

转载 作者:行者123 更新时间:2023-12-02 05:37:17 26 4
gpt4 key购买 nike

我正在尝试根据字符串的长度过滤掉一个字符串数组。总的来说,我对 Objective C 和 OOP 完全陌生。

wordList=[[stringFile componentsSeparatedByCharactersInSet:[NSCharacterSetnewlineCharacterSet]] mutableCopy];
for (int x=0; x<[wordList count]; x++) {
if ([[wordList objectAtIndex:x] length] != 6) {
[wordList removeObjectAtIndex:x];
}else {
NSLog([wordList objectAtIndex:x]);
}
}

for (int x=0; x<[wordList count]; x++) {
NSLog([wordList objectAtIndex:x]);
}

else语句中的NSLog只会输出6个字母的单词,但是第二个NSLog输出的是整个数组。我在这里错过了什么?也欢迎任何清理/改进代码的一般指示。

最佳答案

根据您认为最容易理解的内容,您可以使用谓词过滤数组或遍历数组并删除对象。您应该选择最容易理解和维护的方法。

使用谓词过滤

谓词是过滤数组或集合的一种非常简洁的方法,但根据您的背景,使用它们可能会感觉很奇怪。您可以像这样过滤数组:

NSMutableArray * wordList = // ...
[wordList filterUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
NSString *word = evaluatedObject;
return ([word length] == 6);
}]];

枚举和删除

您不能在枚举数组时修改它,但您可以记下所有要删除的项目,并在枚举整个数组后批量删除它们,如下所示:

NSMutableArray * wordList = // ...
NSMutableIndexSet *indicesForObjectsToRemove = [[NSMutableIndexSet alloc] init];
[wordList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSString *word = obj;
if ([word length] != 6) [indicesForObjectsToRemove addIndex:idx];
}];
[wordList removeObjectsAtIndexes:indicesForObjectsToRemove];

关于objective-c - NSMutableArray removeObjectAtIndex 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11486706/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com