2

特定のケースをマッピングするのが難しい これはこことまったく同じ問題です

product:{
     "id": 123,
     "name": "Produce RestKit Sample Code",
     "description": "We need more sample code!",
     "tasks": [
         {"name": "Identify samples to write", "assigned_user_id":1},
         {"name": "Write the code", "assigned_user_id": 1},
         {"name": "Push to Github", "assigned_user_id": 1},
         {"name": "Update the mailing list", "assigned_user_id": 1}]
}

そのため、タスク オブジェクトのマッピングを作成しました。タスクの NSSET との関係を持つ製品オブジェクトのマッピングを作成しました。

しかし、新しいデータを解析するたびに、タスクがコア データで複製されます。(正常な原因 ID なし)

2 つのソリューション:

  1. 新しいタスクが見つかった場合、現在の製品のタスクを削除できます。
  2. 製品 ID を使用して、タスクの ID を作成できます

このソリューションを実装する方法がわかりません。どんな助けでも素晴らしいでしょう。

4

1 に答える 1

1

このタスク オブジェクトをどのようにマッピングするかはよくわかりませんが、次の方法NSDataで JSON 文字列を解析します。

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                           options:0
                                                             error:&error];

その場合、NSDictionary「product」という 1 つのキーで を取得し、そのキーのオブジェクトは別の辞書です。NSDictionary「タスク」をキーに持つオブジェクトはNSArray、4 つのNSDictionaryオブジェクトのうちの 1 つです。

さて、その JSON の抜粋は有効な JSON ではありませんでしたが、より広範な JSON ファイルのリーフに過ぎなかったと思います。ただし、テスト目的のために、JSON ファイルが次のようであると仮定しましょう。

{
    "product" : {
        "id": 123,
        "name": "Produce RestKit Sample Code",
        "description": "We need more sample code!",
        "tasks": [
                  {"name": "Identify samples to write", "assigned_user_id": 1},
                  {"name": "Write the code", "assigned_user_id": 1},
                  {"name": "Push to Github", "assigned_user_id": 1},
                  {"name": "Update the mailing list", "assigned_user_id": 1}]
    }
}

次に、その JSON を次のように解析できます。

NSString *filename = [[NSBundle mainBundle] pathForResource:@"13628140" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:filename];
NSError *error;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data
                                                           options:0
                                                             error:&error];

NSDictionary *product = dictionary[@"product"];
NSArray *tasks = product[@"tasks"];
NSDictionary *firstTask = tasks[0];
NSString *firstName = firstTask[@"name"];
NSString *firstAssignedUserId = firstTask[@"assigned_user_id"];

または、代わりに、タスクを列挙したい場合:

NSDictionary *product = dictionary[@"product"];
NSArray *tasks = product[@"tasks"];

[tasks enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSDictionary *task = obj;
    NSLog(@"Task \"%@\" is assigned to %@", task[@"name"], task[@"assigned_user_id"]);
}];

NSArrayそれをtasksコアデータに保存する方法を尋ねているだけですか?

于 2012-11-29T14:51:11.847 に答える