发生了什么:我是swift的新手,我还不太了解CoreData,但我在youtube上关注了一些教程,所以我可以学习它。现在,当我运行我的应用程序时,它崩溃,然后出现错误"致命错误:在展开可选值时意外发现nil"
详细信息:此代码来自一个帮助新人快速使用CoreData的教程。
以下是代码:
导入UIKit 导入CoreData
类SwiftCoreDataHelper:NSObject {
class func directoryForDatabaseFilename()->NSString{
return NSHomeDirectory().stringByAppendingString("/Library/Private Documents")
}
class func databaseFilename()->NSString{
return "database.sqlite";
}
class func managedObjectContext()->NSManagedObjectContext{
var error:NSError? = nil
NSFileManager.defaultManager().createDirectoryAtPath(SwiftCoreDataHelper.directoryForDatabaseFilename() as String, withIntermediateDirectories: true, attributes: nil, error: &error)
let path:NSString = "\(SwiftCoreDataHelper.directoryForDatabaseFilename()) + \(SwiftCoreDataHelper.databaseFilename())"
let url:NSURL = NSURL(fileURLWithPath: path as String)!
let managedModel:NSManagedObjectModel = NSManagedObjectModel.mergedModelFromBundles(nil)!
var storeCoordinator:NSPersistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedModel)
if !(storeCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error:&error ) != nil){
if (error != nil){
println(error!.localizedDescription)
abort()
}
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = storeCoordinator
return managedObjectContext
}
class func insertManagedObject(className:NSString, managedObjectConect:NSManagedObjectContext)->AnyObject{
let managedObject:NSManagedObject = NSEntityDescription.insertNewObjectForEntityForName(className as String, inManagedObjectContext: managedObjectConect) as! NSManagedObject
return managedObject
}
class func saveManagedObjectContext(managedObjectContext:NSManagedObjectContext)->Bool{
if managedObjectContext.save(nil){
return true
}else{
return false
}
}
class func fetchEntities(className:NSString, withPredicate predicate:NSPredicate?, managedObjectContext:NSManagedObjectContext)->NSArray{
let fetchRequest:NSFetchRequest = NSFetchRequest()
let entetyDescription:NSEntityDescription = NSEntityDescription.entityForName(className as String, inManagedObjectContext: managedObjectContext)!
fetchRequest.entity = entetyDescription
if (predicate != nil){
fetchRequest.predicate = predicate!
}
fetchRequest.returnsObjectsAsFaults = false
let items:NSArray = managedObjectContext .executeFetchRequest(fetchRequest, error: nil)!
return items
}
}
然后,它在这里崩溃了:
**let entetyDescription:NSEntityDescription = NSEntityDescription.entityForName(className as String, inManagedObjectContext: managedObjectContext)!** // Crashes right here, "Thead 1: EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)
我该怎么做才能解决这个错误?我在这个帖子里待了3天,我不知道在哪里跑!
提前致谢。
更新
这是我的代码:
导入UIKit 导入CoreData
类MainViewController:UIViewController,UITableViewDataSource,UITableViewDelegate {
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var tableView: UITableView!
var namesListArray:NSMutableArray = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
loadData()
}
func loadData() {
namesListArray.removeAllObjects()
let moc:NSManagedObjectContext = SwiftCoreDataHelper.managedObjectContext()
let results:NSArray = SwiftCoreDataHelper.fetchEntities(NSStringFromClass(Recipe), withPredicate: nil, managedObjectContext: moc)
for recipe in results {
let singleRecipe:Recipe = recipe as! Recipe
let recipeDict:NSDictionary = ["identifier":singleRecipe.identifier, "recipelabel":singleRecipe.recipelabel, "recipeimage":singleRecipe.recipeimage]
namesListArray.addObject(recipeDict)
}
tableView.reloadData() }
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return namesListArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell:CustomCellTableViewCell = tableView.dequeueReusableCellWithIdentifier("customCell", forIndexPath: indexPath) as! CustomCellTableViewCell
let recipeDict:NSDictionary = namesListArray.objectAtIndex(indexPath.row) as! NSDictionary
let recipeName = recipeDict.objectForKey("recipelabel") as! String
let imageData:NSData = recipeDict.objectForKey("recipeimage") as! NSData
let recipeImage: UIImage = UIImage(data: imageData)!
cell.customLabel.text = recipeName
var recipeImageFrame:CGRect = cell.customImage.frame
recipeImageFrame.size = CGSizeMake(75,75)
cell.customImage.frame = recipeImageFrame
cell.customImage.image = recipeImage
return cell
}
}
谓词NSPredicate?无无
也许错误在这附近?如果是这样,我无法看到它。有什么想法吗?
再次感谢!!!
答案 0 :(得分:0)
传递的className
很可能在其中有拼写错误,因此您无法从模型中检索实体。将传入的内容与模型所期望的内容进行比较,您将发现错误。
在该方法中打印出className。打印出来的是什么?它与模型中的相匹配吗?类名很少与实体名相同。
答案 1 :(得分:0)
我有类似的错误。对我有用的是,在您的实体'食谱'中尝试添加以下内容
@objc(配方) class Recipe:NSManagedObject { ... }
您正在将Recipe暴露给Objective-C。 我正在使用Xcode 7.3.1。
还有一件事需要检查。 确保在数据模型检查器中具有您的模块字段是空白的。要到达那里,请单击.xcdatamodelId并在右侧窗格中单击。