2017-04-11 61 views
0

即時通訊目前在開發我的應用程序書籤功能。此功能的流程來自新聞列表屏幕,用戶選擇閱讀新聞,然後在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並嘗試了一段時間才弄清楚,但它仍然沒有工作。所以請任何人都可以幫我解決它。非常感謝你。

+0

好像你在你的'cellForRow'上做錯了,打印'list [indexPath.row]'和'dict.articles [indexPath.row]'看看有沒有什麼東西 – Tj3n

+0

應用程序在視圖出現之前崩潰了,但是我想來到了可能會從ArticleList對象的問題,它的陣列始終包含在numberOfRowsInSection方法只有1元 –

+0

日誌列表計數。 https://github.com/realm/realm-cocoa/issues/4248 –

回答

0

貌似dict.articles列表爲空當你標來獲取其indexPath.row的對象。