我发现了很多关于如何将数据编码为key => value
样式的文档,但是我如何提取密钥&数组中的值?我目前正在使用NSArray
。
我所追求的是obj-c与php foreach($array as $k => $v)
的对等
答案 0 :(得分:0)
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);
}
答案 1 :(得分:-1)
如果您的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
}
///(OR)
[yourdict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
NSLog(@"Key -> value of Dict is:%@ = %@", key, object);
}];
希望它可以帮助你......!