3

I was looking at the TableSearch example code from Apple. It looks like that they have a NSArray for all the content, and a NSMutableArray for filtered content. And then if the filter is on, then they would show the NSMutableArray. If it is off, they would show the NSArray that has all the data.

1) I was wondering if this is a common implementation for filters since I haven't done much filtering before.

2) To add to that question, if I had a filter of four different categories, would I still use one NSMutableArray that shows the filtered content when the filter is on? Or do I create four different NSMutableArrays for each different type of filter, and then show that list depending on which filter is on.

Assuming that the common implementation is to have an NSArray for the list, I'm getting confused if creating the arrays of filtered list up front is expensive if I were to do four different NSMutableArrays, or if depending on the click from the user of what filter option they select, should I create the NSMutableArray on the fly, and then reload the [tableView reloadData];

Thanks.

2 Answers 2

2

I don't have that sample app in front of me, but you typically would filter using a predicate, so it would be helpful for you to review the docs on NSPredicate.

So when you want to change the filter, you do so by changing the predicate. You don't have to create all filtered results. You only create the one you need at any given moment.

With arrays, you can filter using code like that shown in this example. The key lines are

NSPredicate *predicate;
predicate = [NSPredicate predicateWithFormat:@"length == 9"];
NSArray *myArray2 = [myArray filteredArrayUsingPredicate:predicate];

Filtering is not always done with arrays. It can be done with NSFetchedResultsControllers if using Core Data. Predicates are used there also, in very much the same way. Predicates can be used for other things, too, including regular expression filtering. It's worth looking at, if you aren't familiar with it.

1

It really depends. If your underlying data is in Core Data, use NSFetchedResultsController and give it NSPredicates. If you have an array of data, it may be easiest to traverse it and create another array of data.

In general, the filter itself is not likely to be as expensive as the overall drawing process (which includes instantiating or recycling table cells). You can do what's easy and profile with Instruments.

Keeping four different arrays is normally not a good idea in terms of memory, which is a scarce resource.

No matter what though, reloadData is going to be involved. (Depending on OS version, perhaps — see the NSFetchedResultsController docs.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.