【问题标题】:iOS, key => value from NSArrayiOS,键 => 来自 NSArray 的值
【发布时间】:2015-01-19 13:23:48
【问题描述】:

我找到了很多关于如何将数据编码为key => value 样式的文档,但是如何从数组中提取键和值呢?我目前正在使用NSArray

我追求的是 obj-c 等效于 php 的 foreach($array as $k => $v)

【问题讨论】:

标签: ios objective-c nsarray


【解决方案1】:

你要找的是 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]);
}

【讨论】:

  • 我又被锁定了 10 分钟来接受这个答案。我将使用 NSDictionary allKeys 来获取键数组。非常感谢
  • 另外,请注意可变数组和字典与非可变数组之间的区别。 Mutable 可以更改,但 non mutable 已设置且不可更改。可变的语法是 NSMutableArray 和 NSMutableDictionary,对于不可变的 NSArray 和 NSDictionary。
【解决方案2】:

一个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);
}

【讨论】:

    【解决方案3】:

    如果你的 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);
    }];
    

    希望对您有所帮助...!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-06
      • 2015-08-25
      • 1970-01-01
      • 2011-03-29
      • 2012-02-24
      相关资源
      最近更新 更多