【发布时间】:2015-01-19 13:23:48
【问题描述】:
我找到了很多关于如何将数据编码为key => value 样式的文档,但是如何从数组中提取键和值呢?我目前正在使用NSArray。
我追求的是 obj-c 等效于 php 的 foreach($array as $k => $v)
【问题讨论】:
标签: ios objective-c nsarray
我找到了很多关于如何将数据编码为key => value 样式的文档,但是如何从数组中提取键和值呢?我目前正在使用NSArray。
我追求的是 obj-c 等效于 php 的 foreach($array as $k => $v)
【问题讨论】:
标签: ios objective-c nsarray
你要找的是 NSDictionary。 NSArray 可通过索引访问:0、1、2 等:
可以像dict[@"key"] 或[dict objectForKey:@"key"]; 一样访问NSDictionary
因此,访问 NSArray 将是:
for( int i = 0; i < [someArray count]-1; i++)
{
NSLog(@"%@", someArray[i]);
}
访问您的 NSDictionary 时:
for (NSString* key in yourDict) {
NSLog(@"%@", yourDict[key]);
//or
NSLog(@"%@", [yourDict objectForKey:key]);
}
【讨论】:
NSDictionary allKeys 来获取键数组。非常感谢
一个NSArray是这样的:
NSArray *array = @[@"One", @"Two", @"Three"];
//Loop through all NSArray elements
for (NSString *theString in array) {
NSLog(@"%@", theString);
}
//Get element at index 2
NSString *element = [array objectAtIndex:2];
//Or :
NSString *element = array[2];
如果你有一个对象并且你要在数组中找到它的索引(对象在数组中必须是唯一的,否则只会返回第一个找到的):
NSUInteger indexOfObject = [array indexOfObject:@"Three"];
NSLog(@"The index is = %lu", indexOfObject);
但如果您使用的是键和值,也许您需要一个 NSDictionary。
NSDictionary 是这样的:
NSDictionary *dictionary = @{@"myKey": @"Hello World !",
@"other key": @"What's up ?"
};
//Loop NSDictionary all NSArray elements
for (NSString *key in dictionary) {
NSString *value = [dictionary valueForKey:key];
NSLog(@"%@ : %@", key, value);
}
【讨论】:
如果你的 NSArray 有多个字典,那么你可以按如下方式获取它们
for(NSDictionary *dict in yourArray)
{
NSLog(@"The dict is:%@",dict);
NSLog(@"The key value for the dict is:%@",[dict objectForKey:@"Name"]);//key can be changed as per ur requirement
}
///(或)
[yourdict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
NSLog(@"Key -> value of Dict is:%@ = %@", key, object);
}];
希望对您有所帮助...!
【讨论】: