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
}
You need to refer to the instance of the FirstViewController, not the actual class definition.
Instead of this:
Try this:
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:
In your table view controller: