user4277177
user4277177

Reputation:

Object loading UIImage crashes the program execution using swift

Program has Simpson class:

import Foundation
import UIKit

class Simpson
{
    var name=""
    var occupation=""
    var image = UIImage()
}

Using this class I declared an array:

import UIKit

class tableVC: UIViewController ,UITableViewDelegate,UITableViewDataSource{

    @IBOutlet weak var tableView: UITableView!
 var mySimpsons=[Simpson]()
    override func viewDidLoad() {
        super.viewDidLoad()
        //tableview setup
        tableView.delegate=self
        tableView.dataSource=self

        //create our Character
        let homer=Simpson()
        homer.name="Homer Simpson"
        homer.occupation="safty inseptor"
        homer.image=UIImage(named: "Homer.png")!

        let bart=Simpson()
        bart.name="Bart Simpson"
        bart.occupation="Student"
        bart.image=UIImage(named: "Bart.png")!

        let marge=Simpson()
        marge.name="Marge Simpson"
        marge.occupation="HomerMaker"
        marge.image=UIImage(named: "Marge.png")!

        let Ned=Simpson()
        Ned.name="Ned Simpson"
        Ned.occupation="Phamacist"
        Ned.image=UIImage(named: "Ned.png")!

         mySimpsons.append(homer)
         mySimpsons.append(bart)
         mySimpsons.append(marge)
         mySimpsons.append(Ned)
}

UITableView delegate's functions are:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return mySimpsons.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell=UITableViewCell()
    cell.textLabel?.text=mySimpsons[indexPath.row].name
    return cell
}

This program is successfully executing but it failed to launch and program crashed when Simpsons object is given image link. i.e

homer.image=UIImage(named: "Homer.png")!

How i can rid of this error? From this link you can download the sample project form correction link.

Upvotes: 0

Views: 70

Answers (1)

krlbsk
krlbsk

Reputation: 1051

That crash occurs because you force unwrapped UIImage instance. Firstly, check if you added those images to your project. Then check whether the image is instantiated correctly by:

if let image = UIImage(named: "Homer") {
   homer.image = image
}

According to UIImage.init(named:) documentation:

For PNG images, you may omit the filename extension. For all other file formats, always include the filename extension.

Upvotes: 2

Related Questions