gpt4 book ai didi

ios - 无法使用 segue 将数组传递给第二个 View Controller

转载 作者:行者123 更新时间:2023-11-29 05:28:12 25 4
gpt4 key购买 nike

我试图将一个数组从 ViewController1 传递到 ViewController2 但无法,同时如果我尝试传递其他任何内容,它都会起作用

我有一个结构如下


struct News {
// var image : String
var title : String
var publisherIcon : String
var publisher : String
var author : String
var time : Int

init(dictionary : [String:Any])
{
self.title = dictionary["title"] as? String ?? ""
self.publisherIcon = dictionary["shortenedLogo"] as? String ?? ""
self.publisher = dictionary["publisher"] as? String ?? ""
self.author = dictionary["author"] as? String ?? ""
self.time = dictionary["timeToRead"] as? Int ?? 0
}
}

在我的 ViewController 1 中我有


var model = [News]()

我的转接代码

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! HomeFeedDarkVC
vc.news = self.model
vc.testfrom = "Test"

}

在我的 ViewController 2 中我有

class HomeFeedDarkVC: UIViewController {

var news = [News]()
var testfrom = ""

override func viewDidLoad() {
super.viewDidLoad()
print(self.news[0].title)
print(testfrom)

}

}

测试成功通过,并打印“Test”,表明segue执行正确

但是数组显示索引超出范围错误,我假设这意味着它是空的并且没有通过

也只是为了测试我也在 View Controller 1 中执行了此操作并且成功打印


print(self.model[0].title)

这意味着模型不为空,但只是没有被传递。我究竟做错了什么?我该怎么做?

编辑:

我应该更清楚模型数组不为空,我将 api 中的 json 数据解析到数组中,然后调用 segue 函数

self.getNews(){response in
for dic in response{
self.model.append(News(dictionary: dic))
}
print(self.model[0].title)
print(self.model[10].publisherIcon)
self.performSegue(withIdentifier: "newsDataFromLogin", sender: self)
let homeVC = self.storyboard?.instantiateViewController(withIdentifier: "HomeFeedDarkVC") as! HomeFeedDarkVC

self.present(homeVC, animated: true)
}

这里 model[0] 和 model[10] 的打印语句都正确打印了各自的数据。模型数组不为空

编辑2:我在prepareSegue函数中添加了这个以显示模型数组如何不为空

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! HomeFeedDarkVC
vc.news = self.model
vc.testfrom = "Test"
vc.titlefrom = self.model[2].title //Added line

}

我在 View Controller 2 中打印了 titlefrom

这是我的日志

How People Redirect Their Careers After Getting Laid Off //model[0].title
https://s3.ap-south-1.amazonaws.com/images.tapin/logo/publishers/harvard_business_review/harvard_shortened.png // model[10].publisherIcon
8 Ways to Read the Books You Wish You Had Time For //titlefrom

最佳答案

var model = [News]() 创建一个空数组。您将其传递给新 Controller ,然后尝试访问该空数组的第一个元素。这是你的问题。
似乎在 Controller 之间传递它没有问题,您只是尝试访问不存在的元素。普通的旧“索引越界”错误,就像错误消息告诉您的那样。添加一些对象,您会发现它有效。如果你想检查它是否通过(但这是一个保证,没有理由不应该),只需执行 print(self.model), print(self.model) .count)print(self.model.first?.title) (这将再次打印 nil,因为第一个元素不存在。)

关于ios - 无法使用 segue 将数组传递给第二个 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57939027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com