I would like to implement saving and fetching of core data directly in a class definition. But when i try to instance it i get the following error: "CoreData: error: Failed to call designated initialiser on NSManagedObject class 'User'". Can anyone tell me what i'm doing wrong? The entity has been created and the class is prefixed with the project name. It works when I have these functions in the ViewController, but am getting the error when i try to implement it in the class.
my code so far is:
import Foundation
import CoreData
import UIKit
@objc(User)
class User: NSManagedObject {
@NSManaged var name: String
@NSManaged var email: String
var users = [NSManagedObject]()
func saveUser(name: String, email: String) {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let entity = NSEntityDescription.entityForName("User",
inManagedObjectContext:
managedContext)
let user = NSManagedObject(entity: entity!,
insertIntoManagedObjectContext:managedContext)
//3
user.setValue(name, forKey: "name")
user.setValue(email, forKey: "email")
//4
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
}
//5
users.append(user)
}
func fetchUser() {
//1
let appDelegate =
UIApplication.sharedApplication().delegate as AppDelegate
let managedContext = appDelegate.managedObjectContext!
//2
let fetchRequest = NSFetchRequest(entityName:"User")
//3
var error: NSError?
let fetchedResults =
managedContext.executeFetchRequest(fetchRequest,
error: &error) as? [NSManagedObject]
if let results = fetchedResults {
users = results
} else {
println("Could not fetch \(error), \(error!.userInfo)")
}
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
if let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) as NSPredicate? {
return emailTest.evaluateWithObject(testStr)
}
return false
}
}
instancing in ViewController:
var userInstance:User = User()