I may have not asked correctly but basically I have two Managed Object Subclass one called Folder another for Items to create different shopping lists. Each Folder has many Items and each Item has one Folder.
The problem I am having is when I delete a Folder the Items associated with it are not also deleted there still hang around in the persistent store.
Does anybody know how I can I also delete the Items that have a relationship with the Folder upon deleting the Folder ?
Folder:
class Folder: NSManagedObject {
#NSManaged var arrayOfItems: [Items]
#NSManaged var date: NSDate
#NSManaged var title: String
#NSManaged var Items: NSSet
}
Items
class Items: NSManagedObject {
#NSManaged var date: NSDate
#NSManaged var index: NSNumber
#NSManaged var item: String
#NSManaged var folder: Folder
}
Deleting a folder:
context.deleteObject(self.selectedNotebook)
// Save the context.
do {
try context.save()
} catch {
print("error saving")
}
Go to your data model file, select the relationship, and on the right side panel select the Delete Rule Cascade
Also, this page can help you understand core data better
Related
I have an object in core data and wanted to send the order to firebase.
The model in core data looks like this:
extension CustomerOrder {
#nonobjc public class func fetchRequest() -> NSFetchRequest<CustomerOrder> {
return NSFetchRequest<CustomerOrder>(entityName: "CustomerOrder")
}
#NSManaged public var reference: String?
#NSManaged public var orderTotal: Double
#NSManaged public var orderID: NSObject?
#NSManaged public var orderDrinks: NSSet?
}
}
From what ive seen firebase likes to follow its own format for transferring models, so I was wondering how I would achieve transmitting this model to my firebase db?
Thanks for any assistance on the approach to take!
Fetch data from CoreData.
https://www.appcoda.com/introduction-to-core-data/
For each entity, post it to Firebase.
https://www.appcoda.com/firebase/
I'm using CoreData with MagicalRecord for store management in my app. I made the xcdatamodel and generated the NSManagedObjects subclasses. My problem is that when I try to use one of the generated accessors for a relationship I get an 'unimplemented SQL generation for predicate' error. This is happening only with one of the generated accessors.
To be more specific, here's the code for the classes I'm using. The problem I have is in the Crop -> Row relationship, which is many to many:
extension Crop {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Crop> {
return NSFetchRequest<Crop>(entityName: "Crop");
}
#NSManaged public var phLevels: Int16
#NSManaged public var row: NSSet?
#NSManaged public var states: NSSet?
// MARK: Generated accessors for row:
extension Crop {
#objc(addRowObject:)
#NSManaged public func addToRow(_ value: Row)
#objc(removeRowObject:)
#NSManaged public func removeFromRow(_ value: Row)
#objc(addRow:)
#NSManaged public func addToRow(_ values: NSSet)
#objc(removeRow:)
#NSManaged public func removeFromRow(_ values: NSSet)
Here's the Row:
extension Row {
#nonobjc public class func fetchRequest() -> NSFetchRequest<Row> {
return NSFetchRequest<Row>(entityName: "Row");
}
#NSManaged public var name: String?
#NSManaged public var crops: NSSet?
#NSManaged public var paddock: Paddock?
}
// MARK: Generated accessors for crops
extension Row {
#objc(addCropsObject:)
#NSManaged public func addToCrops(_ value: Crop)
#objc(removeCropsObject:)
#NSManaged public func removeFromCrops(_ value: Crop)
#objc(addCrops:)
#NSManaged public func addToCrops(_ values: NSSet)
#objc(removeCrops:)
#NSManaged public func removeFromCrops(_ values: NSSet)
I'm trying to add a Row to the Crop:
plantingCrop?.addToRow(row)
And there's when I get the
unimplemented SQL generation for predicate
Or if i try the other way around the same result:
row.addToCrops(plantingCrop!)
I'm a bit lost here, plantingCrop is generated ok, i use other accessors before I set the row in the crop and they are working ok (they are one-to-many relationships), I tried to regenerate the subclasses and the same result. In the debugger I can see at that point that the relationship is faulting when I try to use it. There's probably something wrong that I'm missing but i cannot find it!
UPDATE
Tried with the code below and the same result.
if let rowsFromCrop = plantingCrop?.mutableSetValue(forKey: "row") {
rowsFromCrop.add(row)
}
EDIT
From Apple Docs, the tick on the transient property means that the attribute is a property that you define as part of the model, but which is not saved to the persistent store as part of an entity instance’s data. Core Data does track changes you make to transient properties, so they are recorded for undo operations. Then says:
"If you undo a change to a transient property that uses nonmodeled information, Core Data does not invoke your set accessor with the old value — it simply updates the snapshot information."
I don't quite completely understand this last line, but it might be that because it was a transient property CD wasn't invoking the right accessor?
I am working on implementing a subclass of PFObject called Event, in Swift. I followed the subclassing guide in Parse's docs, but I don't understand how and where to write the code that adds data to the ivars. Below is my what I have in my class so far, including the ivars.
#NSManaged var name:String
#NSManaged var time:NSDate
#NSManaged var favorite:Bool
#NSManaged var moderator: String
#NSManaged var speakers: [String]
#NSManaged var slides: PFFile?
#NSManaged var files: [PFFile]?
override class func initialize() {
var onceToken : dispatch_once_t = 0;
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
class func parseClassName() -> String! {
return "Event"
}
Normally, I would implement an init() constructor or something similar. However, I realized that the data would already be contained in the PFObject's dictionary when it is fetched from the server. Where would I put the code to copy across and put this data in the instance vars from the PFObject's dictionary? This is presuming that I would instantiate the object via a query and fetch from the server and not locally using the object() method.
Based on the comment by deadbeef above, I realized that I can just use Swift's getters and setters for computed properties to read and write values from the PFObject's data dictionary.
For example a property that I intend to have as read-only:
var name:String
{
return self["name"] as String
}
And a property I intend to have as read-write
var favorite:Bool
{
get {
return self["favorite"] as Bool
}
set(value) {
self["favorite"] = value
}
}
You don't have to copy manually.
That's the Parse framework job. The objects will be populated with data after a fetch.
I'm having an issue using relationships in Core Data. I created my data model including the following entities: User, Conversation, Message, Participant - each containing a one-to-many relationship with the entity following it. I generated the classes for each entity using Editor -> Create NSManagedObject Subclass, and it correctly created the .Swift files for each class. The project builds, but when attempting to create and save a new user I get the following error:
2014-12-01 12:31:28.450 Messenger[2627:151403] CoreData: warning: Unable to load class named 'Messenger.User' for entity 'User'. Class not found, using default NSManagedObject instead.
I made sure that my entity classes were prefixed with the project/module name (Messenger.User).
I also added "#ObjC(User)" directly above the User class, and added "-ObjC" to "Other Linker Flags" for the project, as suggested by people in various other posts. These are all the fixes that I could find, but I still get the same error. Here's what my User class looks like, for reference:
import Foundation
import CoreData
#objc(User)
class User: NSManagedObject {
#NSManaged var api : API
#NSManaged var username: String
#NSManaged var userID: String
#NSManaged var passcode: String
#NSManaged var conversations: NSSet
func findConversations(sourceView: MessengerViewController) {
api.findConversations(sourceView)
}
func addConversation(newConversation: Conversation) {
self.addConversationObject(newConversation)
}
}
extension User {
func addConversationObject(value: Conversation) {
var items = self.mutableSetValueForKey("conversations");
items.addObject(value)
}
func removeConversationObject(value: Conversation) {
var items = self.mutableSetValueForKey("conversations");
items.removeObject(value)
}
}
Does anybody have an idea what else I did wrong? I've tried every fix I could come across, but nothing has seemed to work so far.
EDIT: The warning occurs when trying to create a new User object, at the third line below:
let userContext : NSManagedObjectContext = self.appDel.managedObjectContext!
let userEntity : NSEntityDescription = NSEntityDescription.entityForName("User", inManagedObjectContext: userContext)!
var newUser = User(entity: userEntity, insertIntoManagedObjectContext: userContext)
Referring to my own answer, maybe you should also make sure you cast any fetch result to the appropriate class. E.g.
let result = context.executeFetchRequest(request, error:nil) as [User]
In response to your code update, you should perhaps try to insert new instances as follows.
var user = NSEntityDescription.insertNewObjectForEntityForName( "User",
inManagedObjectContext: context) as User
I have a dictionary which I have all data that I want to insert into database as new object. The problem is when I try to cast the newly created object it gives me exception in:
libswift_stdlib_core.dylib`swift_dynamicCast:
part of assembly code.
The code that i am using is like this:
var group:Group
if (array.count == 0) {
group = NSEntityDescription.insertNewObjectForEntityForName("Group", inManagedObjectContext:appDelegate.managedObjectContext) as Group
}
and the structure of Group class is like this:
#objc(Group)
class Group:NSManagedObject{
#NSManaged var createDate:NSString
#NSManaged var groupPictureUrl:NSString
#NSManaged var groupTypeId:NSString
#NSManaged var isDepartment:NSString
#NSManaged var lastMessageRead:NSString
#NSManaged var name:NSString
#NSManaged var unreadMessageCount:NSString
#NSManaged var groupId:NSString
#NSManaged var lastSync:NSString
}
I have also a subclass of NSManagedObject named AppData which has the same structure with Group class. And at inserting part of my code if I replace Group with AppData it works and I can insert into AppData table. As I said before they have the same structure except parameters. But when I try to insert Group object it gives me dynamic cast exception. How can I solve this problem?
I solved the problem by initializing the entity object differently, if you implement the initiation method from super class(NSManagedObject) like: (in Group.swift)
init(entity: NSEntityDescription!, insertIntoManagedObjectContext context: NSManagedObjectContext!) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
you can create the object like this:
var desc:NSEntityDescription = NSEntityDescription.entityForName("Group",inManagedObjectContext:appDelegate.managedObjectContext)
var group:Group = Group(entity:desc, insertIntoManagedObjectContext: appDelegate.managedObjectContext)
most of solutions i have read was making the initiation like this:
var group:Group = NSEntityDescription.insertNewObjectForEntityForName("Group", inManagedObjectContext:appDelegate.managedObjectContext) as Group
so this was the problem and object could not be casted to custom managed object class with this way. Thanks to everyone.