CoreData auto-generated swift code error - macos

I'm new to swift and core data. I've created a simple OS X application using core data. So in the AppDelegate.swift there is a lot of auto-generated code. I just want to save name and lastname when I press a button in the MainMenu.xib I've been searching around for a while on how to use core data in a OS X application using swift but with no success.
This is my code:
#IBAction func buttonAggiungiNewDipendentePressed(sender : AnyObject) {
println("Button pressed from popover");
//var AppDel:AppDelegate = (NSApplication.sharedApplication().delegate as AppDelegate)
let context = self.managedObjectContext!
var nome = popAggiungiDipendenteNome.stringValue;
var cognome = popAggiungiDipendenteCognome.stringValue;
var newUser = NSEntityDescription.insertNewObjectForEntityForName("Dipendenti", inManagedObjectContext: context) as NSManagedObject
newUser.setValue(nome, forKey: "nome")
newUser.setValue(cognome, forKey: "cognome")
context.save(nil)
popover.performClose(true);
}
I'm getting the following crash: Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP,subcode=0x0) inside the auto generate code in AppDelegate.swift:
var managedObjectModel: NSManagedObjectModel? {
// Creates if necessary and returns the managed object model for the application.
if let mom = _managedObjectModel {
return mom
}
let modelURL = NSBundle.mainBundle().URLForResource("ElencoTelefonicoAkhela2", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL)
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
When it tries to return the managedObjectModel. Any idea? Thanx in advance

instead of insertNewObjectForEntityForName use:
let en = NSEntityDescription.entityForName("Photo", inManagedObjectContext: context)
let photo:Photo = Photo(entity:en, insertIntoManagedObjectContext:context)

Related

Xcode custom framework store data differently for widget & main app

Core data in my custom framework stores data separately for its widget and main app. The widget doesn't load data stored from the main app. Is there any solution to fetch data from a widget that is stored from main app?
Code in framework:
import Foundation
import CoreData
public class CoreDataManager {
public static let shared = CoreDataManager()
let identifier = "com.Appnap.DataBaseFramework"
let model = "CoreDataModel"
lazy var persistentContainer: NSPersistentContainer = {
let messageKitBundle = Bundle(identifier: self.identifier)
let modelURL = messageKitBundle!.url(forResource: self.model, withExtension: "momd")!
let managedObjectModel = NSManagedObjectModel(contentsOf: modelURL)
let container = NSPersistentContainer(name: self.model, managedObjectModel: managedObjectModel!)
container.loadPersistentStores { (storeDescription, error) in
if let err = error{
fatalError("❌ Loading of store failed:\(err)")
}
}
return container
}()
//MARK: - Append data
public func createTask(task: String){
let context = persistentContainer.viewContext
let contact = NSEntityDescription.insertNewObject(forEntityName: "Task", into: context) as! Task
contact.id = UUID()
contact.taskdescription = task
do {
try context.save()
print("✅ Person saved succesfuly")
} catch let error {
print("❌ Failed to create Person: \(error.localizedDescription)")
}
}
//MARK: - Fetch data
public func fetch() -> [String] {
var data = [String]()
let context = persistentContainer.viewContext
let fetchRequest = NSFetchRequest<Task>(entityName: "Task")
do{
let allTask = try context.fetch(fetchRequest)
for (_,task) in allTask.enumerated() {
print(task.taskdescription!)
data.append(task.taskdescription!)
}
}catch let fetchErr {
print("❌ Failed to fetch Person:",fetchErr)
}
return data
}
}
I just called the "createTask" & "fetch" functions from main app and widget. But main app and widget stores data in different container.

How to fetch using string in swift

I was just wondering how would I be able to use a searched barcode to fetch using Core Data in Swift. I'm basically passing a barcode to a static func method, but how would I be able to use that to fetch the data from the Core Data?
Here is the barcode when detected:
func barcodeDetected(code: String) {
// Let the user know we've found something.
let alert = UIAlertController(title: "Found a Barcode!", message: code, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Search", style: UIAlertActionStyle.Destructive, handler: { action in
// Remove the spaces.
let trimmedCode = code.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
// EAN or UPC?
// Check for added "0" at beginning of code.
let trimmedCodeString = "\(trimmedCode)"
var trimmedCodeNoZero: String
if trimmedCodeString.hasPrefix("0") && trimmedCodeString.characters.count > 1 {
trimmedCodeNoZero = String(trimmedCodeString.characters.dropFirst())
// Send the doctored barcode
ProductDetailsViewController.searchCode(trimmedCodeNoZero)
} else {
// Send the doctored barcode
ProductDetailsViewController.searchCode(trimmedCodeString)
}
self.navigationController?.popViewControllerAnimated(true)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
My Product Class:
import UIKit
import Foundation
import CoreData
class ProductDetailsViewController: UIViewController, NSFetchedResultsControllerDelegate {
#IBOutlet weak var productLabel: UILabel!
#IBOutlet weak var priceLabel: UILabel!
#IBAction func addProduct(sender: AnyObject) {
let AppDel = UIApplication.sharedApplication().delegate as? AppDelegate
let context:NSManagedObjectContext = (AppDel?.managedObjectContext)!
let ent = NSEntityDescription.entityForName("Products", inManagedObjectContext: context)
var newProduct = ProductItem(entity: ent!, insertIntoManagedObjectContext: context)
newProduct.title = productLabel.text
//newProduct.price = priceLabel.text
/*context.save(nil)
print(newProduct)
print("Object Saved")*/
}
private(set) var PRODUCT_NAME = ""
private(set) var PRODUCT_PRICE = ""
private var menuItems:[ProductItem] = []
static func searchCode(codeNumber: String) -> String{
let barcodeNumber = codeNumber
return barcodeNumber
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func viewDidLoad() {
super.viewDidLoad()
productLabel.text = "Scan a Product"
priceLabel.text = ""
NSNotificationCenter.defaultCenter().addObserver(self, selector: "setLabels:", name: "ProductNotification", object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
I already added the items into Core Data successfully and was able to load all items into a table in my app. Now with the barcode scanned I want to be able to just load the products with the barcode and i'm stuck on that part. As you can see my static fun searchCode is receiving the barcode from barcodeDetected but what should I do next to fetch it? Thanks.
EDIT:
Core Data Entity
import Foundation
import CoreData
#objc(ProductItem)
class ProductItem: NSManagedObject{
#NSManaged var barcodeNum:String?
#NSManaged var box_height:NSNumber?
#NSManaged var box_length:NSNumber?
#NSManaged var box_width:NSNumber?
#NSManaged var price:NSNumber?
#NSManaged var sku:String?
#NSManaged var weight:NSNumber?
#NSManaged var title:String?
}
To fetch the correct ProductItem, you need to use a predicate (see the Apple Documentation here). In your case, you could use something like this:
let AppDel = UIApplication.sharedApplication().delegate as? AppDelegate
let context:NSManagedObjectContext = (AppDel?.managedObjectContext)!
let fetchRequest = NSFetchRequest(entityName: "ProductItem")
fetchRequest.predicate = NSPredicate(format: "barcodeNum == %#",codeNumber)
let results = try! context.executeFetchRequest(fetchRequest) as! [ProductItem]
if results.count > 0 { // great, you found (at least one) matching item
let scannedProduct = results[0]
// from here you can access the attributes of the product
// such as title, price, sku, etc.
...
} else { // not found
...
}
Note that I've use try! for brevity, but in practice you should use proper do ... catch syntax and handle any errors.
I'm not clear why you are using a static func in the ProductDetailsViewController; a common approach would be to use the above fetch within your barcodeDetected method, and then to segue to the ProductDetailsViewController passing the relevant ProductItem for display/editing or whatever. Or to display an alert view if the product was not found.

Swift 3.0 NSFetchRequest error [duplicate]

In Swift 2 the following code was working:
let request = NSFetchRequest(entityName: String)
but in Swift 3 it gives error:
Generic parameter "ResultType" could not be inferred
because NSFetchRequest is now a generic type. In their documents they wrote this:
let request: NSFetchRequest<Animal> = Animal.fetchRequest
so if my result class is for example Level how should I request correctly?
Because this not working:
let request: NSFetchRequest<Level> = Level.fetchRequest
let request: NSFetchRequest<NSFetchRequestResult> = Level.fetchRequest()
or
let request: NSFetchRequest<Level> = Level.fetchRequest()
depending which version you want.
You have to specify the generic type because otherwise the method call is ambiguous.
The first version is defined for NSManagedObject, the second version is generated automatically for every object using an extension, e.g:
extension Level {
#nonobjc class func fetchRequest() -> NSFetchRequest<Level> {
return NSFetchRequest<Level>(entityName: "Level");
}
#NSManaged var timeStamp: NSDate?
}
The whole point is to remove the usage of String constants.
I think i got it working by doing this:
let request:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Level")
at least it saves and loads data from DataBase.
But it feels like it is not a proper solution, but it works for now.
The simplest structure I found that works in 3.0 is as follows:
let request = NSFetchRequest<Country>(entityName: "Country")
where the data entity Type is Country.
When trying to create a Core Data BatchDeleteRequest, however, I found that this definition does not work and it seems that you'll need to go with the form:
let request: NSFetchRequest<NSFetchRequestResult> = Country.fetchRequest()
even though the ManagedObject and FetchRequestResult formats are supposed to be equivalent.
Here are some generic CoreData methods that might answer your question:
import Foundation
import Cocoa
func addRecord<T: NSManagedObject>(_ type : T.Type) -> T
{
let entityName = T.description()
let context = app.managedObjectContext
let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)
let record = T(entity: entity!, insertInto: context)
return record
}
func recordsInTable<T: NSManagedObject>(_ type : T.Type) -> Int
{
let recs = allRecords(T.self)
return recs.count
}
func allRecords<T: NSManagedObject>(_ type : T.Type, sort: NSSortDescriptor? = nil) -> [T]
{
let context = app.managedObjectContext
let request = T.fetchRequest()
do
{
let results = try context.fetch(request)
return results as! [T]
}
catch
{
print("Error with request: \(error)")
return []
}
}
func query<T: NSManagedObject>(_ type : T.Type, search: NSPredicate?, sort: NSSortDescriptor? = nil, multiSort: [NSSortDescriptor]? = nil) -> [T]
{
let context = app.managedObjectContext
let request = T.fetchRequest()
if let predicate = search
{
request.predicate = predicate
}
if let sortDescriptors = multiSort
{
request.sortDescriptors = sortDescriptors
}
else if let sortDescriptor = sort
{
request.sortDescriptors = [sortDescriptor]
}
do
{
let results = try context.fetch(request)
return results as! [T]
}
catch
{
print("Error with request: \(error)")
return []
}
}
func deleteRecord(_ object: NSManagedObject)
{
let context = app.managedObjectContext
context.delete(object)
}
func deleteRecords<T: NSManagedObject>(_ type : T.Type, search: NSPredicate? = nil)
{
let context = app.managedObjectContext
let results = query(T.self, search: search)
for record in results
{
context.delete(record)
}
}
func saveDatabase()
{
let context = app.managedObjectContext
do
{
try context.save()
}
catch
{
print("Error saving database: \(error)")
}
}
Assuming that there is a NSManagedObject setup for Contact like this:
class Contact: NSManagedObject
{
#NSManaged var contactNo: Int
#NSManaged var contactName: String
}
These methods can be used in the following way:
let name = "John Appleseed"
let newContact = addRecord(Contact.self)
newContact.contactNo = 1
newContact.contactName = name
let contacts = query(Contact.self, search: NSPredicate(format: "contactName == %#", name))
for contact in contacts
{
print ("Contact name = \(contact.contactName), no = \(contact.contactNo)")
}
deleteRecords(Contact.self, search: NSPredicate(format: "contactName == %#", name))
recs = recordsInTable(Contact.self)
print ("Contacts table has \(recs) records")
saveDatabase()
This is the simplest way to migrate to Swift 3.0, just add <Country>
(tested and worked)
let request = NSFetchRequest<Country>(entityName: "Country")
Swift 3.0 This should work.
let request: NSFetchRequest<NSFetchRequestResult> = NSManagedObject.fetchRequest()
request.entity = entityDescription(context)
request.predicate = predicate
I also had "ResultType" could not be inferred errors. They cleared once I rebuilt the data model setting each entity's Codegen to "Class Definition". I did a brief writeup with step by step instructions here:
Looking for a clear tutorial on the revised NSPersistentContainer in Xcode 8 with Swift 3
By "rebuilt" I mean that I created a new model file with new entries and attributes. A little tedious, but it worked!
What worked best for me so far was:
let request = Level.fetchRequest() as! NSFetchRequest<Level>
I had the same issue and I solved it with the following steps:
Select your xcdatamodeld file and go to the Data Model Inspector
Select your first Entity and go to Section class
Make sure that Codegen "Class Definition" is selected.
Remove all your generated Entity files. You don't need them anymore.
After doing that I had to remove/rewrite all occurences of fetchRequest as XCode seem to somehow mix up with the codegenerated version.
HTH
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
func loadItemsCategory() {
let request: NSFetchRequest<Category> = Category.fetchRequest()
do {
categoryArray = try context.fetch(request)
} catch {
print(error)
}
tableView.reloadData()
}

Swift - How to define core data context in OS X

Thanks to online tutorials I have been using core data with swift and iOS. To define a context I have used
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
How do I define the context when writing an OS X application?
I define it that way:
lazy var context: NSManagedObjectContext? = {
let appDel = NSApplication.sharedApplication().delegate as! AppDelegate
if let moc = appDel.managedObjectContext {
return moc
} else {
return nil
}
}()
You could also have done:
let context = (NSApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
UIApplication has changed to NSApplication
'as!' changed to 'as'

Whats the easiest way to empty and save a Core Data Table in Swift?

So I have a entity, which I am treating as a simple Database Table in iOS8 XCODE and SWIFT. I want to delete every entry in the table. Permanently. So when I start up the app again they do not reload.This is my code.
func deleteAllItems(){
println("All Items are being DELETED")
var count:Int = 0
while (HBCContactList.count > 0){
let AppDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let MOContext: NSManagedObjectContext = AppDel.managedObjectContext!
MOContext.deleteObject(HBCContactList[0] as NSManagedObject)
HBCContactList.removeAtIndex(0)
var error:NSError? = nil
if !MOContext.save(&error){
abort()
}
tableView.reloadData()
}
It looks like it loads. When its finished on the screen there is nothing in UITableView and all is good. However If I write code to return me the entity via a fetch statement and do a count on the number of records. It still says there is over 150 results.
Thoughts? Am I even in the right ball park?
One solution is to fetch the objects and delete them.
Here is an example (make sure you specify your own entity) :
// If you'll be using the Managed Object Contexte often,
// you might want to make it a lazy property :
lazy var managedObjectContext : NSManagedObjectContext? = {
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
return managedObjectContext
}
else {
return nil
}
}()
func deleteData() {
let context = self.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName: "yourEntity")
fetchRequest.includesPropertyValues = false // Only fetch the managedObjectID (not the full object structure)
if let fetchResults = context.executeFetchRequest(fetchRequest, error: nil) as? [yourEntity] {
for result in fetchResults {
context.deleteObject(result)
}
}
var err: NSError?
if !context.save(&err) {
println("deleteData - Error : \(err!.localizedDescription)")
abort()
} else {
println("deleteData - Success")
}
}

Resources