Im currently develop a bookmark function in my app. The flow of this function is from the News list screen, user choose to read news, then in the WebView will contain a bookmark button. After the bookmark button is pressed, the news will be stored in Realm, then displayed in Bookmark ViewController. However, when i pushed into the BookmarkVc, app crashed with below exception:
I think the problem come from the ArticleList when it always contain only 1 element even if i added more. Thus it leads to the index out of range problem:
Here is my code for webViewVC and bookmark button action:
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)
}
And for the 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
}
This is the first time i use Realm and tried for a whole time to figure out, but it still no work. So please any one can help me to solve it. Thank you very much.
下标以获取其indexPath.row
的对象时, dict.articles
列表dict.articles
为空。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.