I have two Entities in CoreData Model (Products and Images), there is a one-to-many relationship between products(one)-images(many). I have also subclassed my entities, and i am trying to populate the database from json file; however i cant seem to understand how to insert images into Images that are related to Products, so that when i pick that product in the app i get all the related images.
extension Products {
@NSManaged var price: NSNumber?
@NSManaged var stock: NSNumber?
@NSManaged var desc: String?
@NSManaged var name: String?
@NSManaged var images: NSSet?
@NSManaged var sales: NSSet?
}
extension Images {
@NSManaged var image: String?
@NSManaged var products: Products?
}
Then the json file data (which i dont have any problem serialising it with NSJSONObjectWithData:
{ "records" : [{ "name" : "Apple iMac 27in", "description" : "The stunning all-in-one iMac features a beautiful 27-inch Retina 5K widescreen display, quad-core Intel Core i5 processors and AMD Radeon R9 M380 graphics processor with 2GB of GDDR5 memory.", "image" : ["imac1.jpg", "imac2.jpg"], "stock" : 32, "price" : 1699.00 }, { "name" : "Apple iPhone 6s Plus 128 GB", "description" : "The moment you use iPhone 6s Plus, you know you’ve never felt anything like it. With just a single press, 3D Touch lets you do more than ever before. Live Photos bring your memories to life in a powerfully vivid way. And that’s just the beginning. Take a deeper look at iPhone 6s Plus, and you’ll find innovation on every level.", "image" : ["iphone6splus1.jpg", "iphone6splus2.jpg", "iphone6splus3.jpg", "iphone6splus4.jpg"], "stock" : 144, "price" : 1042.00 } ]}
this is the function which i use to populate the database in the AppDelegate just after checking that the database is empty.
func fillDatabase() {
let jsonURL = NSBundle.mainBundle().URLForResource("products", withExtension: "json");
let data = NSData(contentsOfURL: jsonURL!);
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(rawValue: 0)) as! Dictionary<String, AnyObject>;
let recordset = jsonData["records"] as! Array<Dictionary<String, AnyObject>>;
for record in recordset {
let product = Products(context: managedObjectContext);
if let name = record["name"] {
product.name = name as? String;
}
if let stock = record["stock"] as? NSNumber {
product.stock = stock;
}
if let price = record["price"] as? Double {
product.price = price;
}
if let desc = record["description"] as? String {
product.desc = desc;
}
if let images = record["image"] as? NSMutableArray {
// *********************************************************
// Im getting the array of images, but dont know where to go from here.
}
do {
try managedObjectContext.save();
} catch let error as NSError {
print(error.debugDescription);
}
}
} catch let error as NSError {
print("error parsing json object: \(error.debugDescription)");
return;
}
}