2013-08-02 32 views
2

我设立一个的NSDictionary对象,以便NSDictionary *scoreObject有球员的名字为它关键,再{ date : score }一个可变字典。为了获取数据,我拉了一个我在Parse中创建的自定义类,它们具有“Name”,“Score”和“createdAt”属性。如何检查一个NSDictionary是否已经有一个键,然后在同一个键下添加项目?

我试图建立结构,使上面可以自动跨越在解析数据中的每一行拉,但我遇到了麻烦,当我有两行数据为同一Name,它被设置为钥匙在我的scoreObject。例如,如果鲍勃有两个分数和两个createdAt日期,我将如何成为ale来简单地扩展值字典,以便两者仍然可以存储在key =“Bob”下?

谢谢!

回答

2

这里有一些代码可以帮助你。您可能需要适应的东西你的情况:

地方分配你的主字典:

// assuming its a property 
self.scoreObject = [NSMutableDictionary new]; 

现在,只要您将设置一个名称一双新的日期/分数,首先检查是否存在该名称已经有任何条目。如果是,则使用先前分配的NSMutableDictionary来存储新对。如果不是,分配一个,然后设置新的一对。

我将它封装在接收日期和分数的方法中。

-(void)addNewScore:(NSString*)score AndDate:(NSString*)date forUsername:(NSString*)username 
{ 

    NSMutableDictionary *scoresForUser = self.scoreObject[username]; //username is a string with the name of the user, e. g. @"Bob" 

    if (!scoresForUser) 
    { 
     scoresForUser = [NSMutableDictionary new]; 
     self.scoreObject[username] = scoresForUser 
    } 

    scoresForUser[date] = score; //setting the new pair date/score in the NSMutableDictionary of scores of that giver user. 

} 

PS:我用的日期和得分作为例如字符串,但您可以通过用户的NSDate或NSNumber的有没有变化,如果你想。

现在,你可以列出用户的所有得分像这样的东西:

-(void)listScoresForUser:(NSString*)username 
{ 
    NSMutableDictionary *scoresForUser = self.scoreObject[username]; 

    for (NSString *date in [scoresForUser allKeys]) { 
     NSString *score = scoresForUser[date]; 
     NSLog(@"%@ - score: %@, createdAt: %@", username, score, date); 
    } 
} 

这样,你应该能够将数据存储在您需要的结构。请让我知道,如果这是你想要的东西。

+1

感谢您的详细解释和编辑你的代码,它的工作真的很好。谢谢! – daspianist

3

尝试这样:

NSDictionary *dict; 
    //this is the dictionary you start with. You may need to make it an NSMutableDictionary instead. 


    //check if the dictionary contains the key you are going to modify. In this example, @"Bob" 
    if ([[dict allKeys] containsObject:@"Bob"]) { 
     //there already is an entry for bob so we modify its entry 
     NSMutableDictionary *entryDict = [[NSMutableDictionary alloc] initWithDictionary:dict{@"Bob"}]; 
     [entryDict setValue:@(score) forKey:@"Date"]; 
     [dict setValue:entryDict forKey:@"Bob"]; 
    } 
    else { 
     //There is no entry for bob so we make a new one 
     NSDictionary *entryDict = @{@"Date": @(score)}; 
     [dict setValue:entryDict forKey:@"Bob"]; 
    } 
相关问题