user3746428
user3746428

Reputation: 11175

Filtering NSMutableArray with NSPredicate

I am currently trying to implement a search bar into my table view. I want to allow users to search through all of their transactions by name, however I am having issues.

I have read tons of examples on this however I am still having problems with my app crashing.

Here is the code I am using for the filter:

func filterContentForSearchText(searchText: NSString) {
    let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)
    searchResults = arrayDataPayments.filteredArrayUsingPredicate(resultPredicate)
}

func searchDisplayController(controller: UISearchDisplayController!, shouldReloadTableForSearchString searchString: String!) -> Bool {
    self.filterContentForSearchText(searchString)
    return true
}

arrayDataPayments is defined as an NSMutableArray and stores sting data. This is my ArrayData class code:

import UIKit

var arrayDataPayments: NSMutableArray = []
var arrayDataCost: NSMutableArray = []
var arrayDataDate: NSMutableArray = []
var arrayDataImage: NSMutableArray = []
var arrayDataValue: NSMutableArray = []

class ArrayData: NSObject {

    func paymentsArray() -> NSMutableArray { return arrayDataPayments }

    func costArray() -> NSMutableArray { return arrayDataCost }

    func dateArray() -> NSMutableArray { return arrayDataDate }

    func imageArray() -> NSMutableArray { return arrayDataImage }

    func valueArray() -> NSMutableArray { return arrayDataValue }
}

Currently my app crashes when there is at least one cell in the table and I tap a key on the keyboard to search for something. I am getting this error:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7f9e88719320> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.'

Upvotes: 0

Views: 3089

Answers (1)

user3746428
user3746428

Reputation: 11175

I discovered the issue. This line of code was the culprit:

let resultPredicate = NSPredicate(format: "name contains[c] %@", searchText)

Changing it to this fixed the issue:

let resultPredicate = NSPredicate(format: "SELF contains[cd] %@", searchText)

Upvotes: 2

Related Questions