Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value (from Viewcontroller)

swift
xcode
ios
coredata

#1

Урок 39 из курса по tableView
Только Я передаю данные из ViewController в TableView.
Записи сохраняются в базе данных
Но не отображаются.

Я обернул текстовые поля в Stack

При передачи информации из текстовых полей ViewController в TableView передает ошибку

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Ошибка выскакивает именно здесь

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: “Cell”, for: indexPath) as! CardsTableViewCell

cell.ThumbnailImageView.image = UIImage(data: self.Cards[indexPath.row].image! as Data)

При повторном запуске выбрасывает из симулятора.


#2


#3

Скорее всего self.Cards[indexPath.row].image пусто


#5

import UIKit

class CardsViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var select: UISegmentedControl!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var imageLabel: UIImageView!


@IBAction func saveButtonPressed(_ sender: UIBarButtonItem) {
    if nameTextField.text == "" || locationTextField.text == "" || textField.text == "" {
        print("Not all fields are filled")
    } else {
        
        if let context = (UIApplication.shared.delegate as? AppDelegate)?.coreDataStack.persistentContainer.viewContext {
            let card = Card(context: context)
            card.name = nameTextField.text
            card.location = locationTextField.text
            card.number = textField.text
            if let image = imageLabel.image {
                card.image = image.pngData()
            }
            do {
                try context.save()
                print("Cохранение удалось!")
            } catch let error as NSError {
                print("Не удалось сохранить данные \(error), \(error.userInfo)")
            }
        }
        
        performSegue(withIdentifier: "unwindSegueFromNewCard", sender: self)
    }
}

var filter : CIFilter!

override func viewDidLoad() {
    super.viewDidLoad()
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
}
    


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    imageLabel.image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage
    imageLabel.contentMode = .scaleAspectFill
    imageLabel.clipsToBounds = true
    dismiss(animated: true, completion: nil)
}


@IBAction func tappedEnter(_ sender: Any) {
    
    if textField.text?.isEmpty ?? true {
        return
    } else {
        if let texttxt = textField.text {
            
            let data = texttxt.data(using: .ascii, allowLossyConversion: false)
            
            if select.selectedSegmentIndex == 0
            {
                filter = CIFilter(name: "CICode128BarcodeGenerator")
            } else {
                filter = CIFilter(name: "CIQRCodeGenerator")
            }
            
            filter.setValue(data, forKey: "inputMessage")
            let transform = CGAffineTransform(scaleX: 5, y: 5)
            let image = UIImage(ciImage: filter.outputImage!.transformed(by: transform))
            imageLabel.image = image
        }
    }
}

func chooseImagePickerAction(source: UIImagePickerController.SourceType) {
    if UIImagePickerController.isSourceTypeAvailable(source) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        imagePicker.sourceType = source
        self.present(imagePicker, animated: true, completion: nil)
    }
}

}


#6

CoreDataStack

import Foundation
import CoreData

class CoreDataStack {
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: “Carder”)
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

            /*
             Typical reasons for an error here include:
             * The parent directory does not exist, cannot be created, or disallows writing.
             * The persistent store is not accessible, due to permissions or data protection when the device is locked.
             * The device is out of space.
             * The store could not be migrated to the current model version.
             Check the error message to determine what the actual problem was.
             */
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext () {
    let context = persistentContainer.viewContext
    if context.hasChanges {
        do {
            try context.save()
        } catch {
            // Replace this implementation with code to handle the error appropriately.
            // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}

}


#7

Не получилось. Не дает сохранить.


#8

а ошибку с unwrapping an Optional value исправили?


#9

Сейчас не активных ошибок.


#10

А в чем тогда проблема?


#11

Проблема в том, что сохраненные данные не отображаются в TableView
А при перезапуске приложения на устройстве, приложение не запускается.

и здесь
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: “Cell”, for: indexPath) as! CardsTableViewCell

выдает ошибку
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value


#12

08
Так выглядит ViewController из которого сохраняется запись для TableView


#13

Я не вижу такой активной ошибки.


#16

@RexHunt правильно Вам говорит, где-то у Вас возвращается nil, вместо значения. Просто распечатайте значение, которое хотите вывести, и где-то увидите nil. В итоге Ваш код должен иметь вид что-то типа:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: “Cell”, for: indexPath) as! CardsTableViewCell
    let image = UIImage(data: self.Cards[indexPath.row].image! as Data)
    print(image) // HERE YOU WILL SEE NIL
    cell.ThumbnailImageView.image =  image

#17

Можно пожалуйста по подробнее:pensive:

Я записал код таким образом:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: “Cell”, for: indexPath) as! CardsTableViewCell
let image = UIImage(data: self.Cards[indexPath.row].image! as Data)
print(image!)

    cell.ThumbnailImageView.image = image
    cell.ThumbnailImageView.clipsToBounds = true
    cell.locationLabel.text = Cards[indexPath.row].location
    cell.numberLabel.text = Cards[indexPath.row].number

    return cell
}

Все равно возвращает nil(


#18


#19


#20

сделайте print(self.Cards[indexPath.row].image)
скорее всего у вас в какой-то ячейке нет картинки


#21

В какой ячейке нет картинки?


#22

закомментируйте работу с картинкой и сделайте просто принт, иначе с вашей ошибкой вы ничего не увидите


#23

Как это нужно закомментировать?