gpt4 book ai didi

ios - Realm 数组索引超出范围

转载 作者:行者123 更新时间:2023-11-30 12:32:25 26 4
gpt4 key购买 nike

我目前正在我的应用程序中开发书签功能。该功能的流程是从新闻列表屏幕,用户选择阅读新闻,然后在WebView中将包含一个书签按钮。按下书签按钮后,新闻将存储在 Realm 中,然后显示在 Bookmark ViewController 中。但是,当我插入 BookmarkVc 时,应用程序崩溃并出现以下异常:

enter image description here

我认为问题出在 ArticleList 上,即使我添加了更多元素,它始终只包含 1 个元素。这样就会导致索引超出范围的问题:

enter image description here

这是我的 webViewVC 和书签按钮操作的代码:

import UIKit
import Realm
import RealmSwift

class WebViewVC: UIViewController {

@IBOutlet weak var webView: UIWebView!
var ulr:String?
let articleList = ArticleList()
var article:NewsArticle?
var list : Results<ArticleList>!
var searchBar:UISearchBar = UISearchBar(frame: CGRect(x: 0, y: 0, width:
250, height: 20))

func drawNavBarUI(navigationItem:UINavigationItem) {
let bookmarkBtn = UIButton(type: .custom)
bookmarkBtn.setImage(UIImage(named: "bookmark"), for: .normal)
bookmarkBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
let item1 = UIBarButtonItem(image: #imageLiteral(resourceName: "favortie"), style: .done, target: self, action: #selector(saveFavoriteArticle))
navigationItem.setRightBarButtonItems([item1,UIBarButtonItem(customView:searchBar)], animated: true)
}

func saveFavoriteArticle() {
articleList.articles.append(article!)
try! realm.write {
realm.add(articleList)
}
print(articleList)
}

override func viewDidLoad() {
super.viewDidLoad()
webView.loadHTMLString(ulr!, baseURL: nil)
drawNavBarUI(navigationItem: self.navigationItem)
}

对于 BookmarkVC:

import UIKit
import RealmSwift

class BookmarksVC: UIViewController,UITableViewDelegate,UITableViewDataSource {

var list : Results<ArticleList> {
get {
return realm.objects(ArticleList.self)
}
}

@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UINib(nibName: "BookmarkCell", bundle: nil), forCellReuseIdentifier: "bookmarkCell")
tableView.delegate = self
tableView.dataSource = self
self.tableView.reloadData()
}


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return list.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let dict = list[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "bookmarkCell", for: indexPath) as! BookmarkCell
cell.titleLabel.text = dict.articles[indexPath.row].title
return cell

}

这是我第一次使用 Realm,并尝试了很长时间来弄清楚,但仍然不起作用。所以请任何人都可以帮我解决这个问题。非常感谢。

最佳答案

当您通过下标获取其 indexPath.row 对象时,dict.articles 列表似乎为空。

关于ios - Realm 数组索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43342801/

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