我需要帮助。我正在尝试使用核心数据来实现应用程序。但是在第52行 -
myHood.setMyHoodImg(addHoodImg.image!))
每次单击按钮创建新引擎盖时都会出错。错误:
"主题1:EXC_BAD_ACCESS(代码= EXC_I386_GPFLT)
以下是代码:
import UIKit
import CoreData
class CreateHoodVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet weak var hooddesc: UITextField!
@IBOutlet weak var addHoodImgBtn: UIButton!
@IBOutlet weak var addHoodImg: UIImageView!
var imagePicker: UIImagePickerController!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker = UIImagePickerController()
imagePicker.delegate = self
addHoodImg.layer.cornerRadius = 4.0
addHoodImg.clipsToBounds = true
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
imagePicker.dismissViewControllerAnimated(true, completion: nil)
addHoodImg.image = image
}
@IBAction func addImage(sender: AnyObject!){
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func createHood(){
if let hoodDescription = hooddesc.text where hoodDescription != ""{
let app = UIApplication.sharedApplication().delegate as! AppDelegate
let context = app.managedObjectContext
let entity = NSEntityDescription.entityForName("MyHood", inManagedObjectContext: context)!
let myHood = MyHood(entity: entity, insertIntoManagedObjectContext: context)
myHood.myHoodDescription = hoodDescription
myHood.setMyHoodImg(addHoodImg.image!)
context.insertObject(myHood)
do {
try context.save()
} catch {
print("Could not save new Hood")
}
}
}
}
答案 0 :(得分:0)
这很简单:
如果你写:
myHood.setMyHoodImg(addHoodImg.image!)
你假设addHoodImg.image存在,但是在第一次运行时,如果没有选择图像,则为NIL。 所以有两种方式:
1)简单地写:
if let hoodDescription = hooddesc.text where hoodDescription != "" , let img = addHoodImg.image {
2)启动时禁用按钮并在选择和图像后启用。
希望得到这个帮助。
ps我在这里使用了一个功能齐全的原型(减少!)。