本文介绍了如何在Objective-C快速计数(循环)的工作? (即:对于(* NSString的在aDictionary ASTRING)...)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的实施定制搜索栏为一个相当复杂的表和所遇到的这个code样式再次。这是从一开始就iPhone开发的书样本:

I'm working on implementing a customized searchBar for a fairly complex table and have come across this code pattern AGAIN. This is a sample from the Beginning iPhone Development book:

- (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];
}

我很好奇的部分是节了(在阵列的NSString *名称)。这是什么做的究竟是什么?它似乎创建为阵列中的每个项目的字符串。此外,它如何工作,词典?

The part I'm curious about is the "for (NSString *name in array)" section. What is this doing exactly? It seems to create a string for every item in the array. Also, how does this work with dictionaries?

谢谢!

推荐答案

这结构是不同的循环样的那一个Objective-C集合中运行在的项目,而不是C数组。第一部分限定了被设置为集合中循环的每次运行一种元素的对象,而第二部分是枚举的集合。例如,code:

This construct is a different kind of for loop that runs over items in an Objective-C collection, rather than a C array. The first part defines an object that is being set to one element in the collection each run of the loop, while the second part is the collection to enumerate. For example, the code:

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

将打印:

foo
bar

它定义一个的NSString *字符串的是,循环的每次运行,被设置为下一个对象的的NSArray *阵列

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

同样,您可以使用枚举与的NSSet(其中没有定义对象的顺序)和NSDictionary中(在那里将枚举存储在字典键的实例调用 valueForKey:上使用该密钥)字典

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).

这是非常类似于C的结构:

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]);
}

它打印:

0
1

这使得code更具可读性和隐藏一些花哨的枚举进入上市对象在一个NSArray,的NSSet,NSDictionary的或的只是一个语法的方法。更多详细信息在Fast Objective-C的2.0编程语言文档的枚举部分。

这篇关于如何在Objective-C快速计数(循环)的工作? (即:对于(* NSString的在aDictionary ASTRING)...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 14:37