1

私のアプリでは、2 つの NSMutableDictionaries を使用しています。それらをbasicDictionaryおよびrefreshDictionaryと呼びましょう。

basicDictionary には値があります。

key:"1" value:"2000" photo:someUIImage //プレイヤーのスコアを追跡したいとしましょう key:"2" value:"1500" photo:someUIImage2 key:"3" value:"1500" photo:someUIImage3キー:"4" 値:"1500" 写真:someUIImage4

キーはプレーヤーIDを表し、残りはかなり明確です。

プレイヤーのスコアを更新するために、20 秒ごとにサーバー API 呼び出しを行います。写真もロードしたくないので、更新呼び出しを使用して、プレーヤー ID と実際のスコアのみを取得します。

したがって、20 秒ごとに、refreshDictionary に保存するデータを取得します。ID とその ID の現在のスコアのみがあります。

refreshDictionary の例:

キー:"1" 値:"2500" キー:"2" 値:"2800" キー:"3" 値:"2700"

I update my tableView with new values. As you can see, I got data only for 3 players, because player 4 has deleted his profile. Now my question is, how do I update basicDictionary to remove player 4?

I know that I'm supposed tu use if (!([basicDictionary isEqualToDictionary:refreshDictionary)) however, it won't tell me at which key they aren't equal.

So what would you guys do? Should I iterate through both of them in nested loop? That seems to consume alot of time when dictionaries are bigger. Oh by the way, my dictionaries are always sorted same way (by players id)

My idea is, that I compare these two dictionaries in

    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
        if (refresh)
        { //compare dictionaries and modify basicDictionary that is data source for my tableview by deleting where key doesn't match
}
4

1 に答える 1

2

このコードは、変更されたキーを提供します。

注:キーの検索は基本的にハッシュマップ(o1 op)にジャンプするため、あなたが話している2番目の配列ウォークについて心配する必要はありません

#import <Foundation/Foundation.h>

@interface NSDictionary (changedKeys)
- (NSArray*)changedKeysIn:(NSDictionary*)d;
@end

@implementation NSDictionary (changedKeys)
- (NSArray*)changedKeysIn:(NSDictionary*)d {
    NSMutableArray *changedKs = [NSMutableArray array];
    for(id k in self) {
        if(![[self objectForKey:k] isEqual:[d objectForKey:k]])
            [changedKs addObject:k];
    }
    return changedKs;
}
@end

int main(int argc, char *argv[]) {
    @autoreleasepool {
        NSDictionary *d1 = @{@"1":@"value",@"2":@"value",@"3":@"value",@"4":@"value"};
        NSDictionary *d2 = @{@"1":@"value",@"2":@"newvalue",@"3":@"value"};

        NSArray *ks = [d1 changedKeysIn:d2];
        NSLog(@"%@", ks);   

    }

    return 0;
}

編集: self.allKeys が self だけに変更されました -- 辞書は既に列挙できます

于 2013-01-27T18:59:01.140 に答える