i'm getting fatal error: unexpectedly found nil while unwrapping an Optional value imagedata is not nil it has a value of 2604750 bytes I don't know why it show this error as I can see img1 is nil why ? any comments !!!
@IBOutlet var img1: UIImageView!
@IBOutlet var img2: UIImageView!
// in viewWillAppear I gave it a default image
self.img1.image = UIImage(named: "dummy.png" )
self.img1.image = UIImage(named: "dummy.png" )
// i changed to send the nsmanagedobject but it's still same error
func setimage(person: NSManagedObject){
let data: NSData = NSData()
if person.valueForKey("picture") as! NSData == data{
if person.valueForKey("tag") as! Int == 1 {
img1.image = UIImage(named: "dummy" )
}else if person.valueForKey("tag") as! Int == 2 {
img2.image = UIImage(named: "dummy")
}}
else{
if person.valueForKey("tag") as! Int == 1 {
img1!.image = UIImage(data: person.valueForKey("picture") as! NSData )
}else if person.valueForKey("tag") as! Int == 2 {
img2.image = UIImage(data: person.valueForKey("picture") as! NSData )
}
}
}
So, you have a simple mistake. In fact your outlets were nil. However, not because you did not assign them in the storyboard, but because the setimage
was called on a different instance of ViewController
.
You have a property view1
in your second view controller which is declared as:
let view1: ViewController = ViewController()
This creates a NEW instance of ViewController
. When you then call view1.setimage
you get a crash because outlets for THIS instance are not connected.
The property in your second view controller should be
var view1: ViewController!
and in your imageTapped
method of the ViewController
you should modify code so it has this line:
view.view1 = self
Forced unwrapping might not be ideal, but it should work as long as you ensure that whenever you instantiate your second view controller you set the view1
property.