【问题标题】:fill NSArray from NSDictionary从 NSDictionary 填充 NSArray
【发布时间】:2014-05-27 08:36:59
【问题描述】:

我是 Objective-C 的新手,我想知道如何从 NSDictionary 填充我的 NSArray?

我的 NSDictionary 看起来像这样:

user =     {
    items =         (
                    {
            nom = nom1;
            prenom = prenom1;
        },
                    {
            nom = nom2;
            prenom = prenom2;
        },
                    {
            nom = nom3;
            prenom = prenom3;
        }
    );
};

它基于 Json,我希望我的数组是这样的:

"prenom1.nom1", "prenom2.nom2", "prenom3.nom3"

我尝试过类似的方法

array = [self.users objectForKey:@"user"]

但结果和我的字典里的一样。

【问题讨论】:

  • 我建议您阅读 Objective-C 基础知识。数组有添加对象,字典有 ObjectForKey。

标签: ios objective-c json nsarray nsdictionary


【解决方案1】:

你可以使用enumerateObjectsUsingBlock -

NSArray *itemsArray=[user objectForKey:@"items"];

NSMutableArray *outputArray=[[NSMutableArray alloc]init];

[itemsArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    [outputArray addObject:[NSString stringWithFormat:@"%@.%@",[obj objectForKey:@"prenom"],[obj objectForKey:@"nom"]]];
}];

outputArray 将以所需格式包含您的姓名

【讨论】:

【解决方案2】:
NSDictionary *users = // your dictionary

NSArray *items = users[@"items"];

NSMutableArray *names = [NSMutableArray array];

for (NSDictionary *item in items) {
    NSString *name = [NSString stringWithFormat:@"%@.%@", item[@"prenom"], item[@"nom"]];

    [names addObject:name];
}

使用您提供的字典,这会将您想要的格式的所有名称添加到 names 数组中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多