首页 > 解决方案 > 使用 Realm DB 和 Swift SearchBar 会导致“索引 0 超出范围(必须小于 0)”。错误

问题描述

各位好人,你们的智慧让我受益匪浅,希望你们能帮助到新手。我正在使用 2 个领域文件,一个用于 tableView,另一个用于搜索栏的过滤结果。搜索时一切正常,但是当我取消搜索时,返回主 tableview 单击一个项目,它崩溃并出现以下错误:我知道它超出范围,但不知道如何解决这个问题。请帮忙,因为我是编程新手。先感谢您。

2020-05-10 17:12:27.991571-0400 RealmTesting[2122:98394] * 由于未捕获的异常“RLMException”而终止应用程序,原因:“索引 0 超出范围(必须小于 0)。” *第一次抛出调用堆栈:( 0 CoreFoundation 0x00007fff23e39f0eexceptionPreprocess + 350 1 libobjc.A.dylib 0x00007fff50ad79b2 objc_exception_throw + 48 2 Realm 0x00000001042f2281 _Z20RLMThrowResultsErrorP8NSString + 657 3 Realm 0x00000001042f33c4 _ZL25translateRLMResultsErrorsIZ28-[RLMResults objectAtIndex:]E3$_6EDaOT_P8NSString + 116 4 Realm 0x00000001042f32f2 -[RLMResults objectAtIndex:] + 98 5 RealmSwift 0x00000001059c529f $s10RealmSwift7ResultsVyxSicig + 239 6 RealmTesting 0x0000000103d75b38 $s12RealmTesting21resultsViewControllerC11viewDidLoadyyF + 504 7 RealmTesting 0x0000000103d7606b $s12RealmTesting21resultsViewControllerC11viewDidLoadyyFTo + 43 8 UIKitCore 0x00007fff4851adb6 -[UIViewController _sendViewDidLoadWithAppearanceProxyObjectTaggingEnabled] + 83 9 UIKitCore 0x00007fff4851fcd4 -[UIViewController loadViewIfRequired] + 1084 10 UIKitCore 0x00007fff485200f1 -[UIViewController视图] + 27 11 UIKitCore 0x00007fff4846f9c1 -[UINavigationController _startCustomTransition:] + 1047 12 UIKitCore 0x00007fff48485869 -[UINavigationController _startDeferredTransitionIfNeeded:] + 698 13 UIKitCore 0x00007fff48486c58 -[UINavigationController __viewWillLayoutSubviews] + 150 14 UIKitCore 0x00007fff48467c28 -[UILayoutContainerView layoutSubviews] + 217 15 UIKitCore 0x00007fff490c9848 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2478 16 QuartzCore 0x00007fff2b4ae3f0 -[CALayer layoutSublayers] + 255 17 QuartzCore 0x00007fff2b4b457b _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 523 18 QuartzCore 0x00007fff2b4bfc12 _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 80 19 QuartzCore 0x00007fff2b408c84 _ZN2CA7Context18commit_transactionEPNS_11TransactionEd + 324 20 QuartzCore 0x00007fff2b43c65f _ZN2CA11Transaction6commitEv + 649 21 UIKitCore 0x00007fff48bf20c0 _afterCACommitHandler + 160 22 CoreFoundation 0x00007fff23d9d2a7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION_ZN2CA7Context18commit_transactionEPNS_11TransactionEd + 324 20 QuartzCore 0x00007fff2b43c65f _ZN2CA11Transaction6commitEv + 649 21 UIKitCore 0x00007fff48bf20c0 _afterCACommitHandler + 160 22 CoreFoundation 0x00007fff23d9d2a7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION_ZN2CA7Context18commit_transactionEPNS_11TransactionEd + 324 20 QuartzCore 0x00007fff2b43c65f _ZN2CA11Transaction6commitEv + 649 21 UIKitCore 0x00007fff48bf20c0 _afterCACommitHandler + 160 22 CoreFoundation 0x00007fff23d9d2a7 __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION+ 23 23 CoreFoundation 0x00007fff23d97d5e __CFRunLoopDoObservers + 430 24 CoreFoundation 0x00007fff23d982aa __CFRunLoopRun + 1226 25 CoreFoundation 0x00007fff23d97ac4 CFRunLoopRunSpecific + 404 26 GraphicsServices 0x00007fff38b2fc1a GSEventRunModal + 139 27 UIKitCore 0x00007fff48bc7f80 UIApplicationMain + 1605 28 RealmTesting 0x0000000103d720cb main + 75 29 libdyld.dylib 0x00007fff519521fd start + 1 ) libc++ abi.dylib:以 NSException 类型的未捕获异常终止

import UIKit
import RealmSwift

let realm = try! Realm()
var results = realm.objects(Dog.self)
var newResults = results
var resultsSearchController = UISearchController()

let dogColor = ""
let dogName = ""
var myIndex = 0

class ViewController: UIViewController, UITableViewDelegate, 
UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate, 
UISearchControllerDelegate{

@IBOutlet weak var dogTableView: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    //let realm = try! Realm()
    //reference the realm file -> Realm() if there is not enough 
room it will throw up an error

    dogTableView.dataSource = self
    dogTableView.delegate = self


    print(Realm.Configuration.defaultConfiguration.fileURL as Any)

    resultsSearchController = ({
        let controller = UISearchController(searchResultsController: 
nil)
        controller.searchResultsUpdater = self
        controller.searchBar.sizeToFit()
        controller.delegate = self
        controller.obscuresBackgroundDuringPresentation = false
        definesPresentationContext = true

        dogTableView.tableHeaderView = controller.searchBar


        return controller
        }) ()


}
override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    self.dogTableView.reloadData()
    myIndex = 0

}

//MARK: UIAlert and UIAlertActions Section

@IBAction func addDogs(_ sender: Any) {
    let realm = try! Realm()

    let alert = UIAlertController(title: "Add Dogs", message: "This 
is for adding dogs", preferredStyle: .alert)
    let cancel_alert = UIAlertAction.init(title: "Cancel", style: . 
 cancel) { (UIAlertAction) in

    }
    alert.addAction(cancel_alert)

    alert.addTextField { (UITextField) in

        }
    alert.addTextField { (UITextField) in
    }

    alert.addAction(UIAlertAction(title: NSLocalizedString("Add 
Dogs", comment: "Default action"), style: .default, handler: { _ in


    let dogName = (alert.textFields?.first)! as UITextField
    let dogColor = (alert.textFields?.last)! as UITextField
    print("you entered dogs color is: \(String(describing: 
dogColor.text))")


    let mybadboy = Dog()
        mybadboy.color = dogColor.text!
        mybadboy.name = dogName.text!
        mybadboy.gender = "Alpha-Male"

        try! realm.write{
            realm.add(mybadboy)
        }
        self.dogTableView.reloadData()
              }))


    self.present(alert, animated: true) {

        }

//MARK: TableView Functions


}

func tableView(_ tableView: UITableView, numberOfRowsInSection 
section: Int) -> Int {
       //let results = realm.objects(Dog.self)
    if (resultsSearchController.isActive) {

            return newResults.count

    } else {
        return results.count

    }

   }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: 
IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: 
"DogCell", for: indexPath)
           // let results = realm.objects(Dog.self)

    if (resultsSearchController.isActive) {

         let object = newResults[indexPath.row]

        cell.textLabel?.text = object.name
        cell.detailTextLabel?.text = object.color
      //myIndex = 0
        return cell

    } else {
    let object = results[indexPath.row]

    cell.textLabel?.text = object.name
    cell.detailTextLabel?.text = object.color

        return cell

    }
  }


 func tableView(_ tableView: UITableView, canEditRowAt indexPath: 
IndexPath) -> Bool {
    return true
}

func tableView(_ tableView: UITableView, commit editingStyle: 
UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

    if (editingStyle == .delete){

        let item = results[indexPath.row]
        try! realm.write{
            realm.delete(item)}

    }
    dogTableView.deleteRows(at: [indexPath], with: .automatic)

    dogTableView.reloadData()


   }

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: 
IndexPath) {

    myIndex = indexPath.row
    performSegue(withIdentifier: "dogDetails", sender: self)
    print("here is my index: \(myIndex)")

    }



//MARK: Searchbar Methods

   func updateSearchResults(for searchController: 
UISearchController) {
    print("Search init: \(myIndex)")
    myIndex = 0
     print("Reset: \(myIndex)")
    if let searchText = searchController.searchBar.text { ///this is 
an incredible feature that took me a while to figure out!
    newResults = results.filter("(name CONTAINS[cd] %@) OR (color 
CONTAINS[cd] %@)", searchText, searchText)

    print("\(String(describing: searchText))")
    print("These are my doggies: \(newResults)")
    }

    dogTableView.reloadData()
    print("After dataTable is reloaded: \(myIndex)")

    }

  func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    dogTableView.reloadData()
 }
//MARK: Perform Segue Actions

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if (segue.identifier == "dogDetails"){
        if (resultsSearchController.isActive) {
            let dogVC = segue.destination as! resultsViewController
                    dogVC.myDoggiesName = newResults[myIndex].name!
                    dogVC.myDoggiesDetails = 
newResults[myIndex].color!
            print("NewResults segued")


       }
        else{
        let dogVC = segue.destination as! resultsViewController
        dogVC.myDoggiesName = results[myIndex].name!
        dogVC.myDoggiesDetails = results[myIndex].color!


          }
      }
    }
}

标签: swiftxcoderealmsearchbar

解决方案


推荐阅读