2013-01-23 32 views
0

我正在使用Parse.com來存儲iOS應用程序的數據。以下代碼成功檢索屬於PFObject「遊戲」的嵌套數組中的所有值。然而,如果我需要查詢另一個數組(與「贏家」(比如說「失敗者」)相同的級別),我無法使其工作,並且數組輸出中的所有值都不會被填充,我想我可以做它們所有在主線程上,而不是嘗試嵌套提取(嵌套塊),但我想知道是否:在Parse.com的PFQuery中檢索嵌套數組的更好方法?

1)是我存儲我的數據的方式禁止我使用Parse的內置查詢/獲取功能正確?數據存儲爲:

PFObject * newGame = [PFObject objectWithClassName:@"Game"]; 
NSArray * winner = [NSArray arrayWithObjects:[_allPlayersPFDictionary objectForKey:[playerData objectAtIndex:0]], [playerData objectAtIndex:1], nil]; 
[_gamePF addObject:winner forKey:@"winners"]; 

2)是否有更好,更清潔的方式做查詢並獲得查詢數據的所有嵌套數組中的所有值?再一次地,獲獎者不是PFObject,而是兩種不同類型的PFObject數組的數組([PFObject fetchAll:(NSArray *)winnersArray]不起作用,因爲數組中的所有對象都必須與PFObject的'類型'相同)。我以這種方式存儲它,因爲每個獲勝玩家都有另一個與它們相關的PFObject(1到多個)「權力」。

這是查詢的作品,但我無法弄清楚如何添加「輸家」到它,並適當填充背景中的所有數據。

PFQuery * gamesQuery = [PFQuery queryWithClassName:@"Game"]; 
[gamesQuery orderByDescending:@"createdAt"]; 
gamesQuery.limit = 30; 
[gamesQuery findObjectsInBackgroundWithBlock:^(NSArray * theGames, NSError * error) { 
    if (error) { 
     NSLog(@"ERROR: There was an error with the Query to get Games!"); 
    } else { 
     for (PFObject * aGame in theGames) { 
      for (NSArray * aWinner in [aGame objectForKey:@"winners"]) { 
       [[aWinner objectAtIndex:0] fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) { 
        if (error) { 
         NSLog(@"ERROR: There was an error with the Query to get Player in winnersArray!"); 
        } else { 
         [PFObject fetchAllIfNeededInBackground:[aWinner objectAtIndex:1] block:^(NSArray *objects, NSError *error) { 
          if (error) { 
           NSLog(@"ERROR: There was an error with the Query to get Powers in winnersArray!"); 
          } else { 
          [_gamesPF addObject:aGame]; 
           NSLog(@"Games from viewDidLoad %@", _gamesPF); 
           [_tableView reloadData]; 
          } 
         }]; 
        } 
       }]; 
      } 
     } 
    } 
}]; 

回答

3

嗯......我覺得有點愚蠢。使用面向對象的方式解析數據模型非常容易。能夠輕鬆地通過重塑數據要解決這個問題:

遊戲(PFObject *)有:

--> winners { (PFObject *), (PFObject *), ..., nil } 
--> losers { (PFObject *), (PFObject *), ..., nil } 

其中一個勝利者作爲創建:

[testWinner1 addObject:power1 forKey:@"power"]; 
[testWinner1 addObject:power2 forKey:@"power"]; 
[testWinner1 addObject:[_playerPFDictionary objectForKey:@"Tom"] forKey:@"player"]; 

,然後讓查詢更容易,只涉及一個背景塊,如下所示:

PFQuery * gameQuery = [PFQuery queryWithClassName:@"TestGame"]; 
[gameQuery includeKey:@"winners.player"]; 
[gameQuery includeKey:@"winners.power"]; 
[gameQuery includeKey:@"losers.player"]; 
[gameQuery includeKey:@"losers.power"]; 
[gameQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { 
    if (error) { 
     NSLog(@"failed"); 
    } else { 
     NSLog(@"testGame: %@", [objects objectAtIndex:0]); 
    } 
}];