我想直接在类定义中实现核心数据的保存和获取。但是当我尝试实例时,我收到以下错误: “CoreData:错误:无法在NSManagedObject类'User'上调用指定的初始化程序。”谁能告诉我我做错了什么?已创建实体,并且该类以项目名称为前缀。它在ViewController中有这些函数时有效,但是当我尝试在类中实现它时会出现错误。
到目前为止,我的代码是: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
}
}
ViewController实例化:
var userInstance:User = User()
答案 0 :(得分:3)
var userInstance:User = User()
在不使用指定的初始化程序的情况下创建用户对象,这会导致错误消息。
如果创建此User
对象的唯一原因
是调用saveUser()
和fetchUser()
方法然后它是
错误的方法,你应该将方法定义为 class 方法:
class func saveUser(name: String, email: String) { ... }
class func fetchUser() { ... }
然后您可以将其称为
User.saveUser(...)
User.fetchUser()
但请注意
var users = [NSManagedObject]()
不应该是User
类的属性。它应该是(例如)
视图控制器的属性,正确键入为
var users = [User]()
并且fetchUser()
方法返回数组。