2016-07-12 16 views
1

私はこのデータ構造をアプリケーションに持っています。あなたが見ることができるように、私は各車のブランドが1つのディーラーによって販売されており、ディーラーが複数のブランドを販売していることを前提としています。リレーショナルデータを保存する方法(コアデータ)

私は、WebサービスからCarBrandデータを取得しています。私は、データを保存する方法一括でデータを取得していますのでcarbrandデータはDelearレコード(したがって、私は、確立された関係を維持する)

に関連付けられているように、これは私の試みです:

 let moc = DataController().managedObjectContext 

     let carbrandEntity = NSEntityDescription.insertNewObjectForEntityForName("carbrandEntity", inManagedObjectContext: moc) as! CarBrand 

     let dealerEntity = NSEntityDescription.insertNewObjectForEntityForName("DealerEntity", inManagedObjectContext: moc) as! Dealer 

     for carbrand in self.carbrandArray { 
      // add our data 
      carbrandEntity.setValue(carbrand[0], forKey: "brandname") 
      carbrandEntity.setValue(carbrand[1], forKey: "makeyear") 

      do { 
       try moc.save() 
      } catch { 
       fatalError("Failure to save context: \(error)") 
      } 

     } 

     dealerEntity.setValue("Steven&Sons", forKey: "name") 
     // How do I save dealer entity so that it is associated with the carbrand data that I just added. 

UPDATE

これは私の試みですが、特定のディーラーを取得すると、私はディーラーの情報を取得しますが、CarBrand(NSSet)は常に空です。

 let moc = DataController().managedObjectContext 

     let carbrandEntity = NSEntityDescription.insertNewObjectForEntityForName("carbrandEntity", inManagedObjectContext: moc) as! CarBrand 

     let dealerEntity = NSEntityDescription.insertNewObjectForEntityForName("DealerEntity", inManagedObjectContext: moc) as! Dealer 

     dealerEntity.setValue("Steven&Sons", forKey: "name") 

     for carbrand in self.carbrandArray { 
      // add our data 
      carbrandEntity.setValue(carbrand[0], forKey: "brandname") 
      carbrandEntity.setValue(carbrand[1], forKey: "makeyear") 


     } 

     do { 
       try moc.save() 
     } catch { 
       fatalError("Failure to save context: \(error)") 
     } 

UPDATE

私はまだどのcarbandデータを取得していませんよ。私はフェッチで間違いを作ってるんだ場合はここで更新されたコード

 let dealerEntity = NSEntityDescription.insertNewObjectForEntityForName("DealerEntity", inManagedObjectContext: moc) as! Dealer 

     dealerEntity.setValue("Steven&Sons", forKey: "name") 

     for c in self.carbrandArray { 
      dealerEntity.carbrand?.setValue(c[0], forKey: "brandname") 
      dealerEntity.carbrand?.setValue(c[1], forKey: "makeyear") 

     } 

は、念のためですが、ここにあなたがチェックアウトするためにだから私は例を単純化し、私のCODE

 let moc = DataController().managedObjectContext 
     let dealerEntity = NSFetchRequest(entityName: "DealerEntity") 

     do { 
      let dealers = try moc.executeFetchRequest(dealerEntity) as! [Dealer] 
      for d in dealers { 
       print(d.carbrand!.count) // Returns 0 
      } 

     } catch { 
      fatalError("Failed to fetch saved data: \(error)") 
    } 
+1

dealerEntityは自分dealerEntityにcarbrandEntitiesのあなたのセットを追加するためのsetValueを使用し、 "carbrand" という名前の属性を持っています。また、個々のcarbandEntityを個別に保存する必要はありません。あなたのdealerEntityを保存すると、Core Dataがそれを行います。あなたはそれにcarbandEntitiesのセットを追加した後であなたのdealerEntityを保存することができます。 –

+0

@ dan-beaulieu答えにあなたのコメントを置き、コード例を表示できますか? – MwcsMac

+0

各カーブランドにカーブランドオブジェクトを挿入する必要があります。カーブランドのディーラーを設定すると、Core Dataがカーブランドをディーラーに追加します。 'エンティティ'(テーブル)と 'オブジェクト'(行)を混在させないでください。 – Willeke

答えて

1

をFETCHです。私は完全に私のために働くここにプロジェクトファイルをアップロードしました。

project file

私は、これは完璧なソリューションであることを主張していないよでも私は、これらのベストプラクティスていると主張しています。 私はちょうどあなたにコンセプトを示し、私はこれにどのようにアプローチしています。

私のデータモデルの外観は次のとおりです。 enter image description here

enter image description here

はここにあなたのタスクを達成するためのコードです。オブジェクトをManaged Objectクラス内に格納するために必要なロジックをカプセル化していることに注目してください。これは必須条件ではありませんが、コードをよりきれいにするために使用しているアプローチです。

ポスト

public final class Post: NSManagedObject { 

    @NSManaged var title: String 
    @NSManaged var body: String 
    @NSManaged var date: NSDate? 
    @NSManaged var comments: Set<Comment>? 

    // Insert code here to add functionality to your managed object subclass 
    public static func insertIntoContext(moc: NSManagedObjectContext, json: AnyObject) { 
     print("\n==============\n Post: \n\(json) \n==============\n") 

     let post = NSEntityDescription.insertNewObjectForEntityForName("Post", inManagedObjectContext: moc) as! Post 

     guard let 
      title = json["title"] as? String, 
      body = json["body"] as? String 
      else { assertionFailure("post body failed"); return } 

     post.title = title 
     post.body = body 
     post.date = NSDate() 

     if let jsonComments = json["comments"] as? [AnyObject] { 

      // pass comments data into our comments class to get inserted into 
      // our context 
      let comments = Comment.returnSet(moc, jsonArray: jsonComments) 
      post.comments = comments 

     } 

     do { 
      try moc.save() 
     } catch let error { 
      print("failed: \n\(error)\n\n<- - - - ->") 
     } 
    } 
} 

コメント

public final class Comment: NSManagedObject { 

    @NSManaged var text: String 
    @NSManaged var name: String 

    public static func returnSet(moc: NSManagedObjectContext, jsonArray: [AnyObject]) -> Set<Comment> { 
     var comments = Set<Comment>() 

     for answer in jsonArray { 
      // this guard statement will continue to the next object if our insert fails 
      guard let c = Comment.insertIntoContext(moc, json: answer) else { continue } 
      comments.insert(c) 
     } 

     return comments 
    } 

    public static func insertIntoContext(moc: NSManagedObjectContext, json: AnyObject) -> Comment? { 
     //print("\ncomment : \n \(json)\n") 
     guard let 
      jsonText = json["text"] as? String, 
      jsonName = json["name"] as? String 
      else { assertionFailure("");return nil } 

     let comment = NSEntityDescription.insertNewObjectForEntityForName("Comment", inManagedObjectContext: moc) as! Comment 

     comment.text = jsonText 
     comment.name = jsonName 

     return comment 
    } 
} 

のViewController

class ViewController: UIViewController { 

    var moc: NSManagedObjectContext! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // you'd get your data from a webserver ideally 
     let postObj : [String: AnyObject] = [ 
      "title" : "some title", 
      "body" : "this is some body text", 
      "comments" : [ 
       [ 
        "text":"some comment", 
        "name":"dan beaulieu" 
       ], 
       [ 
        "text":"another comment comment", 
        "name":"user30646" 
       ], 
       [ 
        "text":"a much wiser comment", 
        "name":"Rob" 
       ] 
      ] 
     ] 

     // then you pass in your object and your context 
     Post.insertIntoContext(moc, json: postObj) 

     let posts = NSFetchRequest(entityName: "Post") 

     do { 
      let posts = try moc.executeFetchRequest(posts) as! [Post] 
      for p in posts { 
       print("------- Comments ------") 
       print(p.comments) // Returns 0 
      } 
     } catch { 
      fatalError("Failed to fetch saved data: \(error)") 
     } 

    } 
} 

AppDelegate

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { 
    // Override point for customization after application launch. 

    guard let vc = window?.rootViewController as? ViewController 
     else { fatalError("Wrong View Controller Type") } 
    vc.moc = managedObjectContext 

    return true 
} 
+0

私はあなたのロジックを組み込みました。すばらしいポストをありがとう! – user30646

+0

それはあなたのために働いてうれしい! –

関連する問題