境界数组索引的范围
问题描述:
即时通讯目前在开发我的应用程序书签功能。此功能的流程来自新闻列表屏幕,用户选择阅读新闻,然后在WebView中将包含书签按钮。按下书签按钮后,新闻将存储在Realm中,然后显示在Bookmark ViewController中。然而,当我推入BookmarkVc,应用程序崩溃与下面的例外:境界数组索引的范围
我觉得从ArticleList来的问题时,它总是包含即使我增加了更多的只有1元。因此,导致了指数超出范围的问题:
这里是我的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并尝试了一段时间才弄清楚,但它仍然没有工作。所以请任何人都可以帮我解决它。非常感谢你。
答
貌似dict.articles
列表为空当你标来获取其indexPath.row
的对象。
好像你在你的'cellForRow'上做错了,打印'list [indexPath.row]'和'dict.articles [indexPath.row]'看看有没有什么东西 – Tj3n
应用程序在视图出现之前崩溃了,但是我想来到了可能会从ArticleList对象的问题,它的阵列始终包含在numberOfRowsInSection方法只有1元 –
日志列表计数。 https://github.com/realm/realm-cocoa/issues/4248 –