gpt4 book ai didi

iphone - Objective-C 中的快速枚举(循环)如何工作? (即: for (NSString *aString in aDictionary). ..)

转载 作者:行者123 更新时间:2023-12-03 18:41:13 24 4
gpt4 key购买 nike

我正在努力为一个相当复杂的表实现一个自定义的搜索栏,并且再次遇到了这个代码模式。这是《iPhone 开发入门》一书中的示例:

- (void)handleSearchForTerm:(NSString *)searchTerm
{
NSMutableArray *sectionsToRemove = [[NSMutableArray alloc] init];
[self resetSearch];

for (NSString *key in self.keys)
{
NSMutableArray *array = [self.names valueForKey:key];
NSMutableArray *toRemove = [[NSMutableArray alloc] init];
for (NSString *name in array)
{
if ([name rangeOfString:searchTerm
options:NSCaseInsensitiveSearch].location == NSNotFound)
[toRemove addObject:name];
}

if ([array count] == [toRemove count])
[sectionsToRemove addObject:key];
[array removeObjectsInArray:toRemove];
[toRemove release];
}
[self.keys removeObjectsInArray:sectionsToRemove];
[sectionsToRemove release];
[table reloadData];
}

我好奇的部分是“for (NSString *name in array)”部分。这到底是在做什么?它似乎为数组中的每个项目创建一个字符串。另外,这如何与字典一起使用?

谢谢!

最佳答案

此构造是一种不同类型的 for 循环,它运行于 Objective-C 集合中的项目,而不是 C 数组。第一部分定义一个对象,每次循环运行时该对象都会设置为集合中的一个元素,而第二部分是要枚举的集合。例如代码:

NSArray *array = [NSArray arrayWithObjects:@"foo", @"bar", nil];
for(NSString *string in array) {
NSLog(string);
}

将打印:

foobar

It's defining an NSString *string that, each run of the loop, gets set to the next object in the NSArray *array.

Similarly, you can use enumeration with instances of NSSet (where the order of objects aren't defined) and NSDictionary (where it will enumerate over keys stored in the dictionary - you can enumerate over the values by enumerating over keys, then calling valueForKey: on the dictionary using that key).

It's extremely similar to the construct in C:

int array[2] = { 0, 1 };
for(int i = 0; i < 2; i++) {
printf("%d\n", array[i]);
}

打印:

01

这只是一种语法方法,可以使代码更具可读性,并隐藏一些用于列出 NSArray、NSSet 或 NSDictionary 中的对象的花哨枚举。 Fast Enumeration 中给出了更多详细信息。 Objective-C 2.0 编程语言文档的部分。

关于iphone - Objective-C 中的快速枚举(循环)如何工作? (即: for (NSString *aString in aDictionary). ..),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1314092/

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