YellowPillow
YellowPillow

Reputation: 4270

Fatal error: unexpectedly found nil

func generateMemedImage() -> UIImage {

    let memeImage = imageView.image!
    let newImageViewOriginAndDimension = self.view.frame
    let originalImageViewOriginAndDimension = imageView.frame
    rescaleImageView(newImageViewOriginAndDimension, image: memeImage)
    print(imageView.frame) // has fatal error unexpectedly found nil
    // other unrelated lines of code
}
func rescaleImageView(originAndDimension: CGRect, image : UIImage) {
    let newImageView : UIImageView = UIImageView(frame: originAndDimension)
    newImageView.image = image
    imageView = newImageView
    print(imageView.frame) // prints fine
}

So I have two functions above can someone explain to me why I am able to run execute print(imageView.frame) without error in the function rescaleImageView but not in the generateMemedImage function?

Am I correct to assume that when I create the newImageView in my generateMemedImage function I'm not actually assigning the imageView variable in my class to newImageView but rather just reassigning the pointer locally in my function?

Upvotes: 0

Views: 52

Answers (1)

Adam
Adam

Reputation: 26917

You are assigning a newly created newImageView into a weak property. Thats why it is not alive in the first method scope. It was simply deallocated. It works in the second method because the object is retained by newImageView constant. You are not adding the new view to a superview, thus it will not be retained (nor you are removing the old one). But creating a new UIImageView doesn't make sense in your case. All you have to do is to assign your image to the existing view. Like following:

func rescaleImageView(originAndDimension: CGRect, image : UIImage) {
    imageView.image = image
    imageView.frame = originAndDimension
}

Upvotes: 1

Related Questions