ios - 意外发现 nil 错误,但所有值都存在

标签 ios swift uicollectionview jsqmessagesviewcontroller

我正在尝试向我的群聊应用程序添加一项功能,如果点击头像,您将被带到包含该用户信息的个人资料页面。我使用的框架 (JSQMesssagesViewController) 有一个用于点击头像的内置方法,didTapAvatarImageView

override func collectionView(_ collectionView: JSQMessagesCollectionView!, didTapAvatarImageView avatarImageView: UIImageView!, at indexPath: IndexPath!) {

    let message = messages[indexPath.item]

    DispatchQueue.main.async {
        let profileVC = ProfileViewController()
        let name = message.senderDisplayName ?? ""
        let gender = self.genderDictionary.value(forKey: message.senderId) as? String ?? ""
        let status = self.statusDictionary.value(forKey: message.senderId) as? String ?? ""
        let avatarString = self.avatarDictionary.value(forKey: message.senderId) as? String ?? ""

        print("\n\nsegueTest: name: \(name), gender: \(gender), avatar: \(avatarString), status: \(status)\n\n")

        profileVC.profileImageView.loadImageUsingCacheWithUrlString(avatarString)
        profileVC.nameLabel.text = name

        switch gender {
        case "male":
            profileVC.nameLabel.textColor = UIColor(hexString: "8097E1")
        case "female":
            profileVC.nameLabel.textColor = UIColor(hexString: "E98BD5")
        default:
            profileVC.nameLabel.textColor = UIColor(hexString: "4F4F4F")
        }

        switch status {
        case "2FCB78":
            profileVC.profileGoingOutLabel.text = "\(name) wants to go out tonight!"
        case "E13F34":
            profileVC.profileGoingOutLabel.text = "\(name) is staying in tonight."
        default:
            profileVC.profileGoingOutLabel.text = "\(name) might want to go out tonight - let them know what the plans are!"
        }

        self.performSegue(withIdentifier: "chatToProfile", sender: self)
    }
}

当我点击头像时,意外发现 nil 崩溃 - 但我的打印语句打印值没有问题,所以它们确实存在。我不确定我哪里出错了,因为 Xcode 没有告诉我 nil 中的哪个值,正如我所说的,我试图传递的值确实存在。

我该怎么做才能解决这个错误?

最佳答案

您需要为通过 profileVC 中的先前 View Controller 显示的所有标签声明字符串属性。

var strName : String

在viewDidLoad中

nameLabel.text = strName

在之前的viewcontroller中

profileVC.strName = yourstring

如果使用 prepareForSegue 那么你需要在这个方法中传递数据而不是 didSelect。

如果你想在不使用 prepareForSegue 的情况下在 didSelect 上传递数据,那么你需要如下创建 viewcontroller 的实例。

修改以下代码,仅作说明

let profileVC = self.storyboard.initiatedwithidentifier: "yourViewcontrollerIdentifier"
profileVC.strName = yourString
self.navigationviewcontroller(profileVc, animated : true) 

关于ios - 意外发现 nil 错误,但所有值都存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44397193/

相关文章:

ios - Object C 到 Swift 自定义类的实现

ios - 如何使用新数据更改 Collection View 单元格数据

swift - 如何为泛型类型添加扩展?

ios - UICollectionView didSelectRowAtIndexPath 不起作用

swift - 如何滚动到 UICollectionView 的底部?

ios - Facebook 图形 API 浏览器 : get friends of friends

objective-c - 如何禁止 NSDate 进行自动时区转换

ios - 将 native html react 为 pdf

ios - 如何在 Swift 2.0 中获取错误消息?

ios - UIButton 无法针对 iPhone 4/5 屏幕尺寸正确调整文本大小。 (使用内在内容大小)