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;
}
}
Given that you set up the relationships correctly in Core Data, you should be able to associate the images by using something like this:
product.images = NSSet(array: imageArray)
Make sure that the imageArray variable contains objects of type Images.
So to summarize, first you need to parse the array and create Images products from that array:
var imageArray = [Images]()
for yourRawImageFromJSON in json{
let image1 = Images(context: managedObjectContext)
// set properties on image
yourImages.append(image1)
}
then, once you have that array of Images, do as I said above (adding it here once again for the sake of completeness):
product.images = NSSet(array: imageArray)
Side note
You should follow the general rule that classes are named in a singular format, so instead of using Images and Products as your class names, you should be using Image and Product. Even though a class represents a generalised concept (much like in a database system, where conceptual classes are named plurally), it's more common and more convenient to use a singular form (for example it's more concise to use let product = Product() as opposed to let product = Products() because the latter conveys the notion that you are instantiating multiple instances, even though that's clearly not the case)
I'm not using CoreData like you do here in my project, but if the other parts of your code are working as intended, this should do the job.
if let images = record["image"] as? NSMutableArray {
for i in 0..<images.count {
let imageObject = Images(context: managedObjectContext)
imageObject.image = images[i]
let images = product.mutableSetValueForKey("images")
images.addObject(imageObject)
}
}
And about the naming of your CoreData objects I agree with the #the_critic, you actually have image objects and product objects. And your product objects has multiple image objects. Which means making the name of the object "image" and name of the relationship "images" in your data model could be much better.
Is not a good practice to store Arrays in core data, Therefore, this is how I would do it:
First: you need to create an Image Object.
extension Images { /* Images+Methods */
class func save(images: [NSDictionary]) -> [Images]? {
let imagesArray = [Images]()
for imageObject in images {
// creates a new Images NSManagedObject
guard let imageEntity = NSEntityDescription.insertNewObjectForEntityForName("Images", inManagedObjectContext: managedObjectContext) as? Images else {
return nil
}
if let image = imageObject["image"] as? String {
imageEntity.image = image
imagesArray.append(imageEntity)
}
}
return imagesArray
}
Then, call the Save(images: [NSDictionary]) method from your previous method.
if let images = record["image"] as? NSMutableArray {
// after what you already have, add the following line
if let images = record["images"] as? NSMutableArray, let imagesObjectArray = Images.save(images) {
product.images = NSSet(array:imagesObjectArray)
}
}
This should do it. Because is creating an Images NSManagedObject for every image that you have.
Hope this helps
P.S
You really need to change your classes name.
Related
How can I fetch data from this array?
Here there is an array which contains some key value pairs, and some keys contain an array of dictionary.
var dataArray = [
["teamName":"Arsenal",
"image":"imageName",
"nextMatch":"in 2 days",
"matches":[
["oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"],
["oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"]
],
"fixtures":[
["oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"HomeTeamScore":"4",
"HomeTeamCards":"True",
"oppositeTeamCards":"false",
"fixturesId":"ID 213432"],
]
],["teamName":"Chelsea",
"image":"imageName",
"nextMatch":"in 2 days",
"matches":[["oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"],["oppositeTeam":"teamName",
"matchTimings":"121212",
"matchId":"ID 213432"]
],"fixtures":[["oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"HomeTeamScore":"4",
"HomeTeamCards":"True",
"oppositeTeamCards":"false",
"fixturesId":"ID 213432"],["oppositeTeam":"teamName",
"oppositeTeamScore":"7",
"HomeTeamScore":"4",
"HomeTeamCards":"True",
"oppositeTeamCards":"false",
"fixturesId":"ID 213432"]
]
],["teamName":"India",
"image":"imageName",
"nextMatch":"null",
"matches":[],
"fixtures":[]
]]
I tried but I was unable to fetch data from this array.
You need to use a Model like this
struct Team {
let teamName:String
let image:String
let nextMatch:String
let matches:[Match]?
let fixtures:[Fixture]?
}
struct Match {
let oppositeTeam:String
let matchTimings:String
let matchId:String
}
struct Fixture {
let oppositeTeam:String
let oppositeTeamScore:String
let HomeTeamScore:String
let HomeTeamCards:String
let oppositeTeamCards:String
let fixturesId:String
}
Next you need to learn about Codeable in swift for which I have attached an article below
Codeable Tutorial in swift
Here is how you can access the arrays/dictionaries defined in your dataArray:
// To access team object at zero index
if let team = dataArray[0] as? [String: Any] {
print("Team: \(team["teamName"])")
// To access matches array of team object at zero index
if let matches = team["matches"] as? [[String: Any]] {
print( matches)
// To access first match
if let match = matches.first {
print(match)
}
}
// Similar to matches access fixtures
if let fixtures = dataArray[0]["fixtures"] as? [[String: Any]] {
print(fixtures)
// To access first fixture
if let fixture = fixtures.first {
print(fixture)
}
}
}
This is ok if you are just prototyping. If you plan to extend this into an actual app creating separate models is the best approach.
You can have a Team model that can contain team name, image and matches and fixtures. For matches you can create a model with matche information in it. Similarly you can create a model for fixtures as well. Your Team class will then contain arrays of Match and Fixture classes like this:
var matches: [Match]
var fixtures: [Fixture]
and your dataArray will be of type
var dataArray: [Team]
Create model for your data using Codable. Parse the data in model using JSON decoder. Then you can use your model wherever you want.
For JSON parsing, you can refer this tutorial:-
https://medium.com/xcblog/painless-json-parsing-with-swift-codable-2c0beaeb21c1
You can fetch data from your Array like this:
for attributesObj in dataArray{
let dicFrmArray = attributesObj as! NSDictionary
if ((dicFrmArray["teamName"] as? NSNull) == nil && dicFrmArray["teamName"] != nil){
print(dicFrmArray[teamName"])
}
}
I'm new to Swift, and coding in general, and have been working on a project where I'd like to create a UICollectionView populated with images from Firebase.
Each section of the UICollectionView would be a category, and each category would contain images related to that category. Each UICollectionView belongs to a parent, and I need to keep track of which parent has which categories, and which images are in each category.
To track the parents, categories, and images, I've set up the Firebase database in the following way (with bowl being the parent, the names of fruit as categories, and the keys are references to image data stored elsewhere in the database):
"bowl" : {
"apple" : {
"-LOM1R4EH9nszjJp0Va5" : true,
"-LOM1aRZT2XCE-6fvLBK" : true,
"-LOM1hSTmRY6wGrWMvIo" : true,
"-LOM1xnvKE6lc7fizomh" : true
},
"banana" : {
"-LOLmQWLXXyiCUwDBwID" : true
},
"pear" : {
"-LOLHakW-EtqevCeHfzl" : true,
"-LOM2DBGGuX5VQLmBz46" : true
},
"orange" : {
"-LOM26_pm6lbJ1D6hVPB" : true
}
}
The image data section of the database looks as follows:
"image" : {
"fruit" : {
"-LOLHakW-EtqevCeHfzl" : {
"description" : "round orange",
"imageURL" : "https://firebasestorage.googleapis.com/1/image1"
},
"-LOLmQWLXXyiCUwDBwID" : {
"description" : "big banana",
"imageURL" : "https://firebasestorage.googleapis.com/1/image2"
},
"-LOM1R4EH9nszjJp0Va5" : {
"description" : "small apple",
"imageURL" : "https://firebasestorage.googleapis.com/1/image3"
}
}
}
The approach I have been attempting to take is to create a dictionary with the image keys in it, then iterate through the image keys to grab the image data associated with each key (such as the imageURL), and then use the imageURL to download the images and populate the UICollectionView.
I've created a struct, as follows to transform the image data:
struct FruitPicture {
let imageURL: String
let description: String
init(imageURL: String, description: String) {
self.imageURL = imageURL
self.description = description
}
init?(snapshot: DataSnapshot) {
guard
let value = snapshot.value as? [String: AnyObject],
let imageURL = value["imageURL"] as? String,
let description = value["description"] as? String else {
return nil
}
self.imageURL = imageURL
self.description = description
}
func toAnyObject() -> Any {
return [
"imageURL": imageURL,
"description": description
]
}
}
I've been able to gather the imageURLs and populate a UICollectionView but it doesn't include the category details, and so far has involved a lot of manipulation of the data via snapshots, dictionaries, arrays, arrays of dictionaries, and so on, from one configuration to another and back again, and I've now become stuck and confused.
I've started looking at using multiple structs and nesting one within the other, like so, but I'm muddled on it all and am spending hours getting nowhere:
struct Picture {
var url: URL
var image: UIImage?
}
struct PictureCategory {
var name: String
var pictures: [Picture]
}
I was hoping for some advice, or roadmap, or details of how you would approach this, or some sample code, or anything to point me in the right direction. Thanks.
Edit to add more info
Thank you Iraniya your reply was very helpful and helped me consider things in a different way, I really appreciate it.
Taking your advice I've written the following which looks up a bowling creates a snapshot of the image meta data within (e.g the fruit and keys associated with that fruit) then uses those keys to create a snapshot of the image data (e.g key, imageURL, description). I then transform both snapshots into dictionaries, and return the dictionaries to the method which called it:
// GET DATA
static func getPicData(forKey bowlKey: String, completion: #escaping ([String : [Any]], [String : [FruitPicture]]) -> Void) {
var imageMetaDict: [String : [Any]] = [:]
var imageDataDict: [String : [FruitPicture]] = [:]
// DEFINE DATABASE TARGET
let ref = Database.database().reference().child("meta").child("bowl").child(bowlKey).child("fruit")
// GET DATA INTO SNAPSHOT AND TRANSFORM INTO DICTIONARY
ref.observeSingleEvent(of: .value, with: { (snapshot) in
guard let dict = snapshot.value as? [String:[String:Any]] else {
return completion([:],[:])
}
// DEFINE DISPATCH GROUP
let dispatchGroup = DispatchGroup()
// ITERATAE THROUGH DICTIONARY
for (categoryObject, fruitData) in dict {
// CREATE ARRAY TO STORE ITEMS
var itemArray = [String]()
// ITERATE THROUGH ITEMS IN FRUIT DATA
for item in fruitData {
// APPEND ITEM.KEY TO ITEM ARRAY
itemArray.append(item.key)
// ENTER DISPATCH GROUP
dispatchGroup.enter()
// USE ITEM.KEY TO GATHER IMAGE DATA
Service.viewPicData(forKey: item.key) { (fruitItem) in
if let fruitItem = fruitItem {
imageDataDict[item.key] = [fruitItem]
}
// EXIT DISPATCH GROUP
dispatchGroup.leave()
}
}
// STORE ARRAY IN DICTIONARY UNDER FRUIT CATEGORY KEY
imageMetaDict[categoryObject] = itemArray
}
// RETURN COMPLETION
dispatchGroup.notify(queue: .main, execute: {
completion(imageMetaDict, imageDataDict)
})
})
}
Each dictionary looks similar to the following:
imageMetaDict
[
"apple": ["-LOM1R4EH9nszjJp0Va5", "-LOM1xnvKE6lc7fizomh", "-LOM1hSTmRY6wGrWMvIo", "-LOM1aRZT2XCE-6fvLBK"],
"pear": ["-LOLHakW-EtqevCeHfzl", "-LOM2DBGGuX5VQLmBz46"],
"banana": ["-LOLmQWLXXyiCUwDBwID"],
"orange": ["-LOM26_pm6lbJ1D6hVPB"]
]
imageDataDict
[
"-LOM26_pm6lbJ1D6hVPB": [myApp.FruitPicture(imageURL: "https://firebasestorage.googleapis.com/1/image1", description: "pear 1")],
"-LOM2DBGGuX5VQLmBz46": [myApp.FruitPicture(imageURL: "https://firebasestorage.googleapis.com/1/image2", description: "banana 1")],
"-LOLmQWLXXyiCUwDBwID": [myApp.FruitPicture(imageURL: "https://firebasestorage.googleapis.com/1/image3", description: "apple 1")]
]
Is this on the right track with what you were suggesting?
From what I understand the next steps are:
Create an array of fruit.keys sorted alphabetically
Use the fruit.keys to get image.keys from 'imageMetaDict'
Use those image.keys to look up the image data (imageURL, etc) in 'imageDataDict'
Transform all of this data into a new FruitDict which contains fruitCategory -> [fruitObject]
Is this similar to what you were suggesting? I'm happy to hear any further pointers, code or suggestions you have, you've really helped me so far!
To store images Create imageDict hash-map(dictionary) with the key you getting from firebase key in image->>fruits eg: "-LOLHakW-EtqevCeHfzl" with value you are getting or the stuct you already create, now when populating fruits-->apple get key from your bowl array or dict and then use that same key to get the image from imagesDict dict(hashmap you just create earlier
now while storing data in firebase make sure each image has unique keys and store that same key in your bowl-->apple->image that way it will be fast and easy to manage as image data and fruits data are mapped using key you get while storing new image :-) if you like the solution I can explain in more dept :-) #HappyCoding
Example
firebase node
"bowl" : {
"apple" : {
"-LOLHakW-EtqevCeHfzl" : true,
"--LOLmQWLXXyiCUwDBwID" : false,
}
}
"image" : {
"fruit" : {
"-LOLHakW-EtqevCeHfzl" : {
"description" : "round orange",
"imageURL" : "https://firebasestorage.googleapis.com/1/image1"
},
"-LOLmQWLXXyiCUwDBwID" : {
"description" : "big banana",
"imageURL" : "https://firebasestorage.googleapis.com/1/image2"
}
}
}
ImageDict
"-LOLHakW-EtqevCeHfzl":{
"description" : "round orange",
"imageURL" : "https://firebasestorage.googleapis.com/1/image1"
},
"-LOLmQWLXXyiCUwDBwID" : {
"description" : "big banana",
"imageURL" : "https://firebasestorage.googleapis.com/1/image2"
}
or
{"-LOLHakW-EtqevCeHfzl":imageStruct1,
"-LOLmQWLXXyiCUwDBwID" :imageStruct2}
now to show image while populating apple
var keys = boul["apple"].allKeys;
if(boul["apple"][keys[0]]){ //value is true show image
var imageUrl = imageDict[keys[0]["imageURL"]; //if using dict
//or
var image = imageDict[key[0]].imageURL //if using struct
}
Now to store parent, categories and there image details
create a Dict called fruitsDict or whatever with dict in side of another dict making key as fruite name eg: "apple":{apples Details like image price etc} but if you only interested in storing images just create list of images which have true value eg: "apple":[key1, key2...]; (keys you get from imageDict.
Now based on your requirement like
Show all category!! then create all category from fruitDict use that as datasource
and use imageDict and fruitsDict for details
Show only specific category like based on seasonal fruits then crate list of those fruits and show those based on imageDict and fruiteDict
HappyCoding :-)
Hi I am trying to populate a view using the response obtained from service but not able to fetch the exact value out of the whole response ,
[
["product_id": PRO161519,
"name": clothes,
"brand_name": Levis,
"discountprice": 0,
"images": <__NSArrayM 0x6000002541c0>(
{
image = "HTTP://i.vinove.com/dnn/backend/uploads/954tshirt_PNG5434.png";
}
)
"category": Accessories,
"price": 23.00
]
]
ProductList-Model
import UIKit
import SpeedLog
let KImages = "images"
let KListImage = "image"
struct ProductList{
var images = ""
var itemArray = [String]()
func bindProductListDataToPopulateView(_ response:[[String:Any]])->[ProductList]{
SpeedLog.print("response value as result",response)
for items in response{
print("items values",items)
}
print("item array",itemArray)
return []
}
}
response value as result
[["image":
item Values
["image":
Kindly help me to get the values images here.
You have to use like this :
for product in products {
if let productImages = product["images"], let images = productImages as? NSArray {
for image in images {
if let image = image as? [String: String] {
print(image["image"])
}
}
}
}
More than likely that JSON response you posted will eventually find its way to you in the form of a key-value Dictionary. You then use a "key" from the JSON you posted to extract the key's corresponding "value". In the snippet you posted, the keys would be the values on the left of the colon (e.g. "product_id", "name", etc).
Now, lets say your dictionary of key-values was called "jsonDictionary". You then would extract the values like so:
let productId = jsonDictionary["product_id"]
let name = jsonDictionary["name"]
If, however, you don't have logic to deserialize that raw JSON data (that you posted in your question) into a Dictionary, then you'll have to start there instead.
I am able to get the last guest dictionary value in the json array saved into core data as a dictionary using the transformable key value however the other guest dictionary values are not saving. Guest is also it's on entity for now but I was hoping to save the guest as a dictionary since this task doesn't require complex relationships. I'm sure I'm looking through the json, the value type for reservation.guest = [AnyHashable: Any]?Any suggestions would be helpful here is my json response https://pastebin.com/J28myW66, thanks
Note: using Alamofire for the HTTP Request. Also haven't included my entire class here as this is the main part of it. Reservation and Guest are both NSManagedObject classes
let managedObjectContext = CoreDataManager.shared.persistentContainer.viewContext
let reservationEntityDescription = NSEntityDescription.entity(forEntityName: "Reservation", in: managedObjectContext)
let guestEntityDescription = NSEntityDescription.entity(forEntityName: "Guest", in: managedObjectContext)
let reservation = Reservation(entity: reservationEntityDescription!, insertInto: managedObjectContext)
let guest = Guest(entity: guestEntityDescription!, insertInto: managedObjectContext)
let url = "\(serverEndpoint)\(path)"
manager?.request(
url
).responseJSON { responseData in
if(responseData.result.error != nil) {
print(responseData.response)
}
else if responseData.result.value != nil{
let json = JSON(responseData.result.value!)
let content = json["data"]
var reservationArray: [String] = []
if let dates = content.array {
for item in dates {
if let str = item["date_time"].string {
reservationArray.append(str)
print(reservationArray)
}
}
}
for (key,obj) in content {
let guestData = obj["guest"]
let guestDict = guestData.dictionaryObject!
reservation.guest = guestDict
reservation.id = obj["id"].stringValue
reservation.dateTime = obj["date_time"].date
reservation.startTime = obj["start_time"].time
reservation.numOfPeople = obj["number_of_people"].intValue as NSNumber?
reservation.status = obj["status"].stringValue
reservation.tables = obj["tables"].arrayObject as! [NSString]?
reservation.reservationCollections = reservationArray as [NSString]?
guest.id = guestData["id"].stringValue
guest.email = guestData["email"].stringValue
guest.name = guestData["full_name"].stringValue
guest.phone = guestData["phone"].stringValue
guest.notes = guestData["notes"].stringValue
}
print("Reservation to be saved\(reservation)")
print("Guest to be saved: \(guest)")
}
}
do {
try reservation.managedObjectContext?.save()
} catch let error as NSError {
fatalError(error.localizedDescription)
}
do {
try guest.managedObjectContext?.save()
} catch let error as NSError {
fatalError(error.localizedDescription)
}
When your code starts, you create one instance of Guest and one instance of Reservation:
let reservation = Reservation(entity: reservationEntityDescription!, insertInto: managedObjectContext)
let guest = Guest(entity: guestEntityDescription!, insertInto: managedObjectContext)
After that you never create any other instances. In your loop you assign values to this instance:
reservation.guest = guestDict
reservation.id = obj["id"].stringValue
...
guest.id = guestData["id"].stringValue
guest.email = guestData["email"].stringValue
...
But since there's only one instance, only the last pass through the loop gets saved. The first time through the loop you assign values to guest and reservation. Every other time, you overwrite the previous values with new ones.
If you want to save a new instance for every pass through the loop, you need to create new instances every time. Move the let guest = ... and let reservation = ... lines inside the loop.
Firstly you need to make design flow bit generic i.e The HTTP request/response, DataBase Part, Model Part and UI part.
Now create a generic model class for your response,
so that the values will bind in single object.
In you core data sub class your table i.e custom NSManagedObject Class.
First convert the dictionary objects [objects in content.array] into respective model class objects.
In that SBPlayer is a model class
Favourite+CoreDataProperties.swift & Favourite+CoreDataClass.swift are custom NSManagedObject class (auto-generated).
Now with every object, you have mapping respective properties in database table and in custom NSManagedObject class.
Map the values and Save it DataBase.
For example: https://github.com/Abhishek9634/ScoreBoard/blob/master/ScoreBoard/ScoreBoard/SBDBManager.swift
Reference : https://github.com/Abhishek9634/ScoreBoard
Very new to Core Data but I've read that I can fetch data that uses Entity relationships. Now, coming from Mysql maybe I'm making too many assumptions, but I have 2 Entities set up with a Relationship between them and I can't fetch the proper data.
Here are my 2 models:
#objc(Categories)
class Categories: NSManagedObject {
#NSManaged var category: String
#NSManaged var exp: String
#NSManaged var order: NSNumber
}
#objc(Techniques)
class Techniques: NSManagedObject {
#NSManaged var korean: String
#NSManaged var order: NSNumber
#NSManaged var spanish: String
#NSManaged var categories: Categories
}
After I created a Relationship from Techniques to Categories, Core Data added this field to the Sqlite DB:
ZCATEGORIES - INTEGER
Let's say I want to fetch all Techniques that belong to the category #3 (with internal ZID: 3)
If I do this:
request.predicate = NSPredicate(format: "categories == %#", 3)
It works. But if I do:
request.predicate = NSPredicate(format: "categories == %#", category.category)
It doesn't work. I understand that it doesn't work because category.category is a String, not an Integer.
My question is:
Do I have to create my own relationhip IDs field in the Category Entity and set that, then reference the Technique like:
request.predicate = NSPredicate(format: "categories == %#", category.categoryID)
?
Isn't there a way to access the Category's internal ID to get this relationship to work?
Or better yet, it would seem to me that there should be an internal mechanish to retrieve these relationships without writing a SQL-like query but just using the Object, something like: Techniques.categores.
Thanks. I haven't found a good answer anywhere.
You are missing an attribute name, so the predicate knows which attribute of the category class to compare. This way you won't need to use the internal unique ID. Although it can be derived (and would work) it's not the way to go with Core Data, who is trying to abstract that information for you.
let categoryPredicate = NSPredicate(format: "categories.category == %#", category.category)
As mentioned setting up an inverse relationship is recommended. It allows Core Data to maintain the consistency of the object graph, and can be used to go from a category to it's techniques.
As you solved friend?
import UIKit
import CoreData
let appdelegado:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let contexto2:NSManagedObjectContext = appdelegado.managedObjectContext
class Consultar: UIViewController {
let marca = Marca()
let modelo = Modelo()
override func viewDidLoad() {
super.viewDidLoad()
//Consultando con diferente contextp
let entityMarca = NSEntityDescription.entityForName("Modelo", inManagedObjectContext: contexto2)
let oderBy = NSSortDescriptor(key: "nombre", ascending: true)
let consulta = NSFetchRequest(entityName: "Modelo")
consulta.sortDescriptors = [oderBy]
//???¿¿???¿¿???¿ HELP
let predicate = NSPredicate(format: "modelo.marca = %#",)
consulta.entity = entityMarca
consulta.predicate = predicate
//let arrayResultado:[NSArray] = try!contexto.executeFetchRequest(consulta) as! [NSArray]
//if let resultado = try?contexto.executeFetchRequest(consulta) where resultado.count > 0{
if let arrayResultado:[NSArray] = try!contexto.executeFetchRequest(consulta) as! [NSArray] where arrayResultado.count > 0{
for x in arrayResultado {
print("\n ====================DATOS RECUPERADOS======================")
print(x)
// print(x.valueForKey("nombre")!)
// print(x.valueForKey("marca")!)
}
}else{
print("Sin modelos")
}
}
}