首页 > 解决方案 > 错误线程 1:EXC_BAD_ACCESS(代码=1,地址=0x30)

问题描述

请告诉我应用程序因错误而崩溃:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x30)

单击用于提醒表格单元格的按钮时(切换到新的视图控制器)。在该行中创建 UILabel 时,该错误出现在类中let label = UILabel ()

let oneLabel: UILabel = {
    let label = UILabel()
    if (UIDevice.current.userInterfaceIdiom == .pad) {
        label.font = UIFont.systemFont(ofSize: 32, weight: .semibold)
        label.numberOfLines = 4
    }
    else {
        label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        label.numberOfLines = 1
    }
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

这是另一个转换到视图控制器的类的代码,为此创建了 UILabel:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let alarm = UIContextualAction(
            style: .normal,
            title: "",
        handler: {(_, _, completion) in
            self.notificationCenter.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
                guard granted else { return DispatchQueue.main.async { self.createAlertForNotifications() } }
                self.notificationCenter.getNotificationSettings { (settings) in
                    guard settings.authorizationStatus == .authorized else { return }
                    DispatchQueue.main.async {
                            let vc = OneViewController()
                            self.parentController!.navigationController?.setViewControllers([vc], animated: false)
                    }
                    completion(true)
                }
            }
        }
        )
        alarm.image = ListImages.alarmImage
        alarm.backgroundColor = .systemPurple
        return UISwipeActionsConfiguration(actions: [alarm])
    }

有时会出现此错误,有时不会出现此错误,并且它可能会出现在第二个 UILabel 中,该 UILabel 是在第一个之后创建的。你怎么能解决这个错误?

标签: swift

解决方案


有时我会出错let dataPicker = UIDatePicker()

在这里,您转到 OneViewController:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let oneObject = isFiltering ? filteredObjects[indexPath.row] : listObjects[indexPath.row]
        let alarm = UIContextualAction(
            style: .normal,
            title: "",
        handler: {(_, _, completion) in
            self.notificationCenter.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
                guard granted else { return DispatchQueue.main.async { self.createAlertForNotifications() } }
                self.notificationCenter.getNotificationSettings { (settings) in
                    guard settings.authorizationStatus == .authorized else { return }
                    DispatchQueue.main.async {
                            let vc = OneViewController()
                            ListNameLabel.oneText = oneObject.name
             self.parentController!.navigationController?.setViewControllers([vc], animated: false)
                    }
                    completion(true)
                }
            }
        }
        )
        alarm.image = ListImages.alarmImage
        alarm.backgroundColor = .systemPurple
        return UISwipeActionsConfiguration(actions: [alarm])
    }

这是带有 UILabel 的类:

import UIKit
class MainView: UIView {
    let oneLabel: UILabel = {
        let label = UILabel()
        if (UIDevice.current.userInterfaceIdiom == .pad) {
            label.font = UIFont.systemFont(ofSize: 32, weight: .semibold)
            label.numberOfLines = 4
        }
        else {
            label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
            label.numberOfLines = 1
        }
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
let sheduleTimeDataPicker: UIDatePicker = {
    let dataPicker = UIDatePicker()
    if #available(iOS 14, *) {
        dataPicker.preferredDatePickerStyle = .inline
        }
    else {
        dataPicker.preferredDatePickerStyle = .compact
    }
    dataPicker.datePickerMode = .dateAndTime
    dataPicker.date = Date()
    dataPicker.minimumDate = Date()
    dataPicker.translatesAutoresizingMaskIntoConstraints = false
    return dataPicker
}()
    let oneView: UIView = {
        let view = UIView()
        view.backgroundColor = .systemGray5
        view.layer.cornerRadius = 15
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.addSubview(oneView)
        oneView.addSubview(oneLabel)
        oneView.addSubview(sheduleTimeDataPicker)
        
        if (UIDevice.current.userInterfaceIdiom == .pad) {
            // oneLabel constraints
            oneLabel.leadingAnchor.constraint(equalTo: oneView.leadingAnchor, constant: 20).isActive = true
            oneLabel.trailingAnchor.constraint(equalTo: oneView.trailingAnchor, constant: -20).isActive = true
            oneLabel.topAnchor.constraint(equalTo: oneView.topAnchor, constant: 20).isActive = true
            oneLabel.heightAnchor.constraint(equalToConstant: 120).isActive = true
            // sheduleTimeDataPicker constraints
        sheduleTimeDataPicker.centerXAnchor.constraint(equalTo: oneView.centerXAnchor).isActive = true
        sheduleTimeDataPicker.topAnchor.constraint(equalTo: oneLabel.bottomAnchor).isActive = true
        }
        else {
            // oneLabel constraints
            oneLabel.leadingAnchor.constraint(equalTo: oneView.leadingAnchor, constant: 10).isActive = true
            oneLabel.trailingAnchor.constraint(equalTo: oneView.trailingAnchor, constant: -10).isActive = true
            oneLabel.topAnchor.constraint(equalTo: oneView.topAnchor, constant: 5).isActive = true
            oneLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 20).isActive = true
        // sheduleTimeDataPicker constraints
        sheduleTimeDataPicker.leadingAnchor.constraint(equalTo: oneView.leadingAnchor, constant: 10).isActive = true
        sheduleTimeDataPicker.trailingAnchor.constraint(equalTo: oneView.trailingAnchor, constant: -10).isActive = true
        sheduleTimeDataPicker.topAnchor.constraint(equalTo: oneLabel.bottomAnchor).isActive = true
        }
        // oneView constraints
        oneView.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 10).isActive = true
        oneView.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -10).isActive = true
        oneView.topAnchor.constraint(equalTo: self.topAnchor, constant: 10).isActive = true
        oneView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -10).isActive = true
    }
    func setContentView(content: OneModel) {
        self.oneLabel.text = content.oneName
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

这是 OneModel 类:

import UIKit
struct ListNameLabel {
    static var oneText = ""
}
struct OneModel {
    var oneName: String
    static func fetchView() -> OneModel {
        return OneModel(oneName: ListNameLabel.oneText)
    }
}

这是 OneViewController 类:

import UIKit
import UserNotifications
class OneViewController: UIViewController {
    var mainView = MainView()
    let notificationCenter = UNUserNotificationCenter.current()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        setupNavigationBar()
        setupView()
    }
    
    // MARK: NavigationBar
    private func setupNavigationBar() {
        let backBarButtonItem = UIBarButtonItem()
        backBarButtonItem.image = ListImages.chevronImage
        backBarButtonItem.action = #selector(backBarButtonItemTapped)
        backBarButtonItem.target = self
        
        navigationItem.leftBarButtonItem = backBarButtonItem
        navigationItem.title = ""
    }

    // MARK: View
    private func setupView() {
        view.backgroundColor = .systemBackground
        view.addSubview(mainView)
        mainView.translatesAutoresizingMaskIntoConstraints = false
        let guide = self.view.safeAreaLayoutGuide
        // mainView constraints
        mainView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
        mainView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
        mainView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
        mainView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
        // fetch
        mainView.setContentView(content: OneModel.fetchView())
    }
}

// MARK: Back
extension OneViewController {
    @objc func backBarButtonItemTapped() {
        let vc = TwoViewController()
        self.navigationController?.setViewControllers([vc], animated: false)
    }
}

// MARK: UNUserNotificationCenterDelegate
extension OneViewController: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.banner, .sound])
        print(#function)
    }
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        print(#function)
    }
}

推荐阅读