【问题标题】:Get values from NSDictionaries从 NSDictionaries 获取值
【发布时间】:2013-02-06 23:32:47
【问题描述】:

我有以下代码:

NSDictionary *dict = @[@{@"Country" : @"Afghanistan", @"Capital" : @"Kabul"},
                     @{@"Country" : @"Albania", @"Capital" : @"Tirana"}];

我想列出许多国家和首都,然后随机化一个国家并将其放在屏幕上,然后用户应该能够选择正确的首都..

  1. 如何输入国家?像dict.Country[0] 之类的?

  2. 代码有什么问题?我收到 错误 "Initializer element is not a compile-time constant" and the warning "Incompatible pointer types initializing 'NSDictionary *_strong' with an expression of type 'NSArray *'.

  3. 我可以在字典中创建第三个字符串,包含一个标志文件..例如

    @"Flagfile" : @"Albania.png"

然后将其放入图像视图中?

我想要一个带有随机数 I 的循环(例如)并放入 like (我知道这是不对的,但我希望你明白这一点)

loop..
....

text= dict.Country[I]; 

button.text= dict.Capital[I];

Imageview=dict.Flagfile[I];
.....
....

【问题讨论】:

  • 您创建字典的代码不正确。 @[ ] 创建一个 NSArray。
  • 创建dict 的语法实际上是创建一个字典数组。
  • 好的,有人告诉我要那样做!那么我该怎么做呢?以及我以后如何获得价值?
  • 在您了解自己在做什么之前,最好使用[NSDictionary dictionaryWith...] 方法。

标签: ios error-handling uiimageview nsdictionary


【解决方案1】:

您的顶级元素是两个 NSDictionary 的 NSArray(@[],带有方括号,组成一个数组)。要访问其中一个字典中的属性,您可以执行 array[index][key],例如array[0][@"Country"] 会给你@"Afghanistan"。如果你做了 NSArray *array = ... 而不是 NSDictionary *dict = ...

如果你想随机选择一个国家,你可以得到一个随机数,得到它 mod 2 (someInteger % 2) 并将它用作你的索引,例如array[randomNumber % 2][@"Country"] 将从您的字典数组中为您提供一个随机的国家/地区名称。

如果您将图像名称存储在字典中,则可以使用 UIImage 的 +imageNamed: 方法加载该名称的图像。

【讨论】:

    【解决方案2】:

    这里有更多关于mbuc91正确思路的完整说明。

    1) 创建一个国家

    // Country.h
    
    @interface Country : NSObject
    
    @property(strong,nonatomic) NSString *name;
    @property(strong,nonatomic) NSString *capital;
    @property(strong,nonatomic) NSString *flagUrl;
    @property(strong,nonatomic) UIImage *flag;
    
    // this is the only interesting part of this class, so try it out...
    // asynchronously fetch the flag from a web url.  the url must point to an image
    - (void)flagWithCompletion:(void (^)(UIImage *))completion;
    
    @end
    
    // Country.m
    
    #import "Country.h"
    
    @implementation Country
    
    - (id)initWithName:(NSString *)name capital:(NSString *)capital flagUrl:(NSString *)flagUrl {
    
        self = [self init];
        if (self) {
            _name = name;
            _capital = capital;
            _flagUrl = flagUrl;
        }
        return self;
    }
    
    - (void)flagWithCompletion:(void (^)(UIImage *))completion {
    
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.flagUrl]];
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:[NSOperationQueue mainQueue]
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                                   if (data) {
                                       UIImage *image = [UIImage imageWithData:data];
                                       completion(image);
                                   } else {
                                       completion(nil);
                                   }
                               }];
    }
    
    @end
    

    2) 现在,在其他类中,使用 Country

    #import "Country.h"
    
    - (NSArray *)countries {
    
        NSMutableArray *answer = [NSMutableArray array];
    
        [answer addObject:[[Country alloc]
                           initWithName:@"Afghanistan" capital:@"Kabul" flagUrl:@"http://www.flags.com/afgan.jpg"]];
    
        [answer addObject:[[Country alloc]
                           initWithName:@"Albania" capital:@"Tirana" flagUrl:@"http://www.flags.com/albania.jpg"]];
    
        return [NSArray arrayWithArray:answer];
    }
    
    - (id)randomElementIn:(NSArray *)array {
    
        NSUInteger index = arc4random() % array.count;
        return [array objectAtIndex:index];
    }
    
    -(void)someMethod {
    
        NSArray *countries = [self countries];
        Country *randomCountry = [self randomElementIn:countries];
        [randomCountry flagWithCompletion:^(UIImage *flagImage) {
            // update UI, like this ...
            // self.flagImageView.image = flagImage;
        }];
    }
    

    【讨论】:

      【解决方案3】:

      您不能以这种方式初始化 NSDictionary。 NSDictionary 是一组 unsorted 键-对象对 - 它的顺序不是静态的,因此您不能像处理数组一样处理它。在您的情况下,您可能需要 NSMutableDictionary,因为您将修改其内容(有关更多信息,请参阅 Apple 的 NSMutableDictionary Class Reference)。

      您可以通过几种方式实现您的代码。使用 NSDictionaries 你会做类似下面的事情:

      NSMutableDictionary *dict = [[NSMutableDictionary alloc]
          initWithObjectsAndKeys:@"Afghanistan", @"Country",
          @"Kabul", @"Capital", nil];
      

      然后您将拥有一系列字典,每个字典包含一个国家/地区的详细信息。

      另一种选择是为每个国家/地区创建一个简单的模型类并拥有一个数组。例如,您可以创建一个名为 Country 的类,Country.h 为:

      #import <Foundation/Foundation.h>
      @interface Country : NSObject
      
      @property (nonatomic, retain) NSString *Name;
      @property (nonatomic, retain) NSString *Capital;
      //etc...
      
      @end
      

      【讨论】:

      • 是的。习惯可能会有点痛苦,但这是最可行的方法,可以防止很多头痛。 Brendon,下面的 danh 代码更好地展示了您正在寻找的功能。我的只是为了说明这个想法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-23
      • 2016-03-10
      • 1970-01-01
      • 2020-12-17
      • 2010-11-02
      相关资源
      最近更新 更多