Hunter
Hunter

Reputation: 1391

Crash when trying to run variable with optional

Hey im getting a crash when I run this code. I know exactly why, but I don't know how to make it not crash.

Code:

// Is Global
weak var modelImage: UIImageView!

// this gets called in a function 

modelImage = UIImageView()
modelImage.frame = CGRect(origin: CGPoint(x: modelSectionInfoCase.frame.width * 0.2, y: modelSectionInfoCase.frame.height * 0.1), size: CGSize(width: modelSectionInfoCase.frame.width / 5, height: modelSectionInfoCase.frame.height / 1.25))
modelImage.alpha = 1.0
modelImage.clipsToBounds = false
modelImage.isUserInteractionEnabled = true
modelImage.backgroundColor = UIColor.clear
modelImage.layer.setAffineTransform(CGAffineTransform(scaleX: -1, y: 1))
modelSectionInfoCase.insertSubview(modelImage, at: 0)
modelSectionInfoCase.bringSubview(toFront: modelImage)

enter image description here

UPDATE:

I need to keep “weak var”, because I’m having a memory Issue. Memory Leak that I’m trying to fix with “weak var”. Not only on this variable but other variables as well with the same logic.

Upvotes: 1

Views: 73

Answers (2)

OOPer
OOPer

Reputation: 47876

You can declare a local variable which keeps strong reference till settings up are finished.

// this gets called in a function 

let modelImage = UIImageView()
modelImage.frame = CGRect(origin: CGPoint(x: modelSectionInfoCase.frame.width * 0.2, y: modelSectionInfoCase.frame.height * 0.1), size: CGSize(width: modelSectionInfoCase.frame.width / 5, height: modelSectionInfoCase.frame.height / 1.25))
modelImage.alpha = 1.0
modelImage.clipsToBounds = false
modelImage.isUserInteractionEnabled = true
modelImage.backgroundColor = UIColor.clear
modelImage.layer.setAffineTransform(CGAffineTransform(scaleX: -1, y: 1))
modelSectionInfoCase.insertSubview(modelImage, at: 0)
modelSectionInfoCase.bringSubview(toFront: modelImage)

self.modelImage = modelImage

(ADDITION)

As I noted in my comments, UIView keeps strong reference to its subviews, so my code works.

But that does not mean you cannot hold another strong reference to any of subviews. If you have no reason to make your property weak, it may be safe to make it strong as in Sh_Khan's answer.

Upvotes: 2

Shehata Gamal
Shehata Gamal

Reputation: 100503

Simply as warning says remove weak

var modelImage: UIImageView!

enter image description here

As you declare the imageView property as weak it won't hold any reference assigned to it , so it will keep it's value nil resulting in the crash , so leave it with it's default strong value

Upvotes: 4

Related Questions