'UIViewController' is not a subtype of 

2019-07-25 17:14发布

I am using a tab bar controller and I'm trying to access the defaults from my other tab bar view controller. I tried this in a different function, also shown below, and it works perfectly, but for some reason it isn't working here. It puts up the error whenever this is called: FirstViewController().defaults. Does anybody have any idea why this is happening?

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{

            let cell = TableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell
            TableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
            var photo: Photo
            let description = FirstViewController().description

            if(searchController.isActive){
                photo = self.filteredPhotos[indexPath.row]
            } else {
                photo = self.photosArray[indexPath.row]
            }
            cell.textLabel!.text = photo.name
            if(FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage != nil){
                cell.imageView?.image = FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage
            }
            print(photo.name)
            print("TableView2Finished")
            return cell
        }

1条回答
不美不萌又怎样
2楼-- · 2019-07-25 17:58

You need to refer to the instance of the FirstViewController, not the actual class definition.

Instead of this:

if(FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage != nil) {
    cell.imageView?.image = FirstViewController().defaults.data(forKey: photo.name + "image") as UIImage
}

Try this:

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let firstViewController = storyboard.instantiateViewController(withIdentifier: "FirstViewController") as! FirstViewController
if(firstViewController.defaults.data(forKey: photo.name + "image") as UIImage != nil) {
    cell.imageView?.image = firstViewController.defaults.data(forKey: photo.name + "image") as UIImage
}

Make sure you set a Storyboard Identifier for your FirstViewController so that you can reference it by the identifier in code.

EDIT #1:

Alternatively, you can save the string name to UserDefaults and access it that way.

In your first view controller:

let defaults = UserDefaults.standard
defaults.set(photo.name, forKey: "FirstImage")

In your table view controller:

let defaults = UserDefaults.standard
if let myImage = defaults.object(forKey: "FirstImage") as? String {
    cell.imageView?.image = UIImage(named: myImage!)
}
查看更多
登录 后发表回答