【问题标题】:How to iterate through an NSArray containing NSDictionaries?如何遍历包含 NSDictionaries 的 NSArray?
【发布时间】:2011-12-09 08:54:52
【问题描述】:

我有一个 NSArray 和 NSDictionaries,每个都有 4 个键值。

我正在为每个 NSDictionary 创建对象并相应地分配键。

如何遍历字典数组并将每个键设置为对象的属性?

我用这段代码创建了如下图所示的数组:

if (muscleArray == nil)
    {
        NSString *path = [[NSBundle mainBundle]pathForResource:@"data" ofType:@"plist"];
        NSMutableArray *rootLevel = [[NSMutableArray alloc]initWithContentsOfFile:path];
        self.muscleArray = rootLevel;
    }

    NSMutableArray *arrayForSearching = [NSMutableArray array];
    for (NSDictionary *muscleDict in self.muscleArray)
        for (NSDictionary *excerciseDict in [muscleDict objectForKey:@"exercises"])
            [arrayForSearching addObject:[NSDictionary dictionaryWithObjectsAndKeys:
                                          [excerciseDict objectForKey:@"exerciseName"], @"exerciseName",
                                          [muscleDict objectForKey:@"muscleName"], @"muscleName",
                                          [muscleDict objectForKey:@"musclePicture"], @"musclePicture", nil]];
    self.exerciseArray = arrayForSearching;

    NSString *path = [[NSBundle mainBundle] pathForResource:@"ExerciseDescriptions"
                                                     ofType:@"plist"];
    NSDictionary *descriptions = [NSDictionary dictionaryWithContentsOfFile:path];

    NSMutableArray *exercises = self.exerciseArray;
    for (NSInteger i = 0; i < [exercises count]; i++) {
        NSDictionary *dict = [[exercises objectAtIndex:i] mutableCopy];

        NSString *exerciseName = [dict valueForKey:@"exerciseName"];
        NSString *description = [descriptions valueForKey:exerciseName];
        [dict setValue:description forKey:@"exerciseDescription"];
        [exercises replaceObjectAtIndex:i withObject:dict];
    }

创建一个对象的代码如下所示:

PFObject *preloadedExercises = [[PFObject alloc] initWithClassName:@"preloadedExercises"];
[preloadedExercises setObject:exerciseName forKey:@"exerciseName"];
[preloadedExercises saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (!error) {
        NSLog(@"Success");
    } else {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

字典数组如下所示:

【问题讨论】:

    标签: iphone objective-c cocoa-touch nsarray nsobject


    【解决方案1】:
    // Assuming you want to do something with all of these objects you're creating
    // We'll start by creating an NSMutableArray
    NSMutableArray *newObjects = [NSMutableArray arrayWithCapacity:arrayOfDictionaries.count];
    
    for (NSDictionary *dictionary in arrayOfDictionaries)
    {
        PFObject *object = [PFObject objectWithClassName:@"preloadedExercises"];
        object.exerciseDescription = [dictionary objectForKey:@"exerciseDescription"];
        object.exerciseName = [dictionary objectForKey:@"exerciseName"];
        object.muscleName = [dictionary objectForKey:@"muscleName"];
        object.musclePicture = [dictionary objectForKey:@"musclePicture"];
    
        // Add object to mutable array
        [newObjects addObject:object];
    }
    

    【讨论】:

    • 我不确定这是否能满足我的要求。我正在尝试遍历数组中的每个字典,并使用 Parse PFObject 为每个字典创建一个对象,如下所示:PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"]; [gameScore setObject:[NSNumber numberWithInt:1337] forKey:@"score"]; [gameScore setObject:@"Sean Plott" forKey:@"playerName"]; [gameScore setObject:[NSNumber numberWithBool:NO] forKey:@"cheatMode"]; [gameScore save]; 他们的文档在这里:parse.com/docs/ios_guide#objects
    • 我已更新我的答案以明确显示 PFObject 实例的创建。完成此操作后,newObjects 将为原始数组中的每个字典包含一个 PFObject。然后您可以遍历这些并在需要时发送-saveInBackground:。
    • 嗨,马克,我不能将saveInBackground 代码添加到您拥有的第一个for loop 中吗?
    • 啊,是的。我认为 parse 提供了一种保存对象集合的方法,但我错了。我还看到每个请求的大小是有限制的,所以是的,您应该在每个循环结束时保存。
    【解决方案2】:

    快速浏览一下您在 cmets 中提到的 Parse SDK,我认为您正在寻找的是:

    NSMutableArray *exercisesArray = [[NSMutableArray alloc] init];
    PFObject *preloadedExercises;
    id value;
    
    // Iterate through your array of dictionaries    
    for (NSDictionary *muscleDict in self.muscleArray) {
        // Create our object
        preloadedExercises = [PFObject objectWithClassName:@"preloadedExercises"];
    
        // For each dictionary, iterate through its keys
        for (id key in muscleDict) {
            // Grab the value
            value = [muscleDict objectForKey:key];
    
            // And assign each attribute of the object to the corresponding values
            [preloadedExercises setObject:value forKey:key];  
        }
    
        // Finally, add this newly created object to your array
        [exercisesArray addObject: preloadedExercises];
    }
    

    【讨论】:

    • 我不确定这是否能满足我的要求。我正在尝试遍历数组中的每个字典,并使用 Parse PFObject 为每个字典创建一个对象,如下所示:PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"]; [gameScore setObject:[NSNumber numberWithInt:1337] forKey:@"score"]; [gameScore setObject:@"Sean Plott" forKey:@"playerName"]; [gameScore setObject:[NSNumber numberWithBool:NO] forKey:@"cheatMode"]; [gameScore save]; 他们的文档在这里:parse.com/docs/ios_guide#objects
    • 哦,实际上,我之前没有遇到过 Parse,并且不确定您的问题代码中的 PFObject 是什么。 PFObject 做了我提到键值编码时所指的事情。让我更新我的答案以说明这应该如何工作。
    • 我认为我们现在走在正确的轨道上。实际上,您可以忽略我发布的所有代码,只需查看我发布的带有键的 NSDictionaries 的 NSArray 的图片,并假设它名为 Array exercises。我只需要遍历它,我不应该发布用于创建该数组的代码,因为它是不必要的。
    • 其实你贴的代码可能是对的,我只要把muscleArray换成exercises就行了
    【解决方案3】:
    for(NSDictionary* dictionary in yourArray){
    // here you can iterate through. and assign every dictionary as you wish to.
    }
    

    【讨论】:

      猜你喜欢
      • 2011-03-22
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多