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.
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.
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.)
Related
I have a data type called Filter which has an NSMutableArray property which holds a bunch of FilterKey objects (different amount of keys for each filter). I have a bunch of these Filter objects stored in an NSMutableArray called Filters.
I have a UITableView for which each row is populated with data from one of the FilterKey objects. My question is, for a given row in the UITableView, how can I use the Filters array to find the right FilterKey (considering I've already put the Filters and Keys in order manually)?
Basically, I know I could just traverse through the Filters array and for each Filter object, traverse through all it's FilterKeys, but I'm wondering is there a better way to do this (ie better data structure, or something that would give me the right object faster?
Sorry if this is confusing if you have any questions please let me know in the comments.
Typically you would use sections and rows for this, where each section is a Filter and each row is a FilterKey.
It sounds like you just want to show the filter keys, and not have section headers for their filters (if I'm reading your post correctly). If you don't actually want headers, that's fine, just return 0 for tableView:heightForHeaderInSection: and nil for tableView:viewForHeaderInSection:.
All of this is really more for convenience than performance. It is unlikely that it will be much faster than running through the filters and adding up the counts of their keys. That kind of operation is extremely fast. But sections/rows maps your data better, so I'd probably use it anyway to keep the code simpler.
You can use NSMutableDictionary which is hash-mapped resulting in faster, easier, readable operations.
If you prefer arrays then there is no need to traverse to search for a specific value, you can use NSPredicate to filter your array.
I have a segment control with 5 items, on selecting every item data is filter on some criteria and a different result is displayed. All the five choices in segment control use the same entity to fetch the data.
Currently i have a fetchresultcontroller and whenever there is a value change in the segment control i fetch data from the same entity with a different predicate and reload the table with new data.
I am looking to optimize this. Am I doing it the right way or what is the right way to do it?
Also what is the best way to change the sorting order between ascending and descending for an already fetched data.
Thanks in adv.
Can you post some code snippets?
If you already fetched a set of MangedObjcts you can reorder the NSArray with a Sort Descirptor: sortedArrayUsingDescriptors
- (NSArray *)sortedArrayUsingDescriptors:(NSArray *)sortDescriptors
If you're only fetching a small number of NSManagedObjects, there probably isn't much optimization to be done. CoreData and its corresponding classes (such as the FetchResultsController you are using, which is designed to work particularly well with UITableViews) do most of the heavy lifting for you.
In terms of the best way to change the sorting order between ascending and descending; this is determined in something like this:
NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:#"someEntityProperty" ascending:YES/NO];
If you set ascending to YES, you'll get your NSManagedObjects back sorted smallest to largest ascending) on the key you provide. If you set it to NO, you'll get them back largest to smallest (descending).
This seems like it may be a trivial question, but I am new to Core Data and to databases.
In my application, I perform a fetch and display the results. Then, based on user input, I need to cull those results down. That is, I need to do a new search on only the results of the first fetch, but based on an entirely different parameter. (Sometimes, the second fetch will be based on an attribute, other times on a to-many relationship.) What is the optimal way to do this?
I have figured out two options to do this, but neither seems very good:
In the first fetch, prefetch all the data needed for the second fetch. Then, don't do a second fetch, but just iterate through the array of results of the first fetch, looking for matches to the new conditions of the second fetch. This method has the disadvantage that I have to trudge thru the array and don't take advantage of performance benefits of Core Data.
For the second fetch, disregard the first and do a brand new fetch with a compound predicate composed of the conditions for the first fetch and those for the second. This has the disadvantage that Core Data must look thru the entire database again to do the same search it already did.
Is there a way, in a second fetch, to tell Core Data to search only thru the entity objects returned in an earlier fetch?
You've pretty much got it figured out.
For the first option, it's pretty easy. You have your array of objects, and you can just do -[NSArray filteredArrayUsingPredicate:] or -[NSMutableArray filterUsingPredicate:] to reduce the array according to your needs. You don't need to actually iterate through the array yourself; just use a predicate like you would with a fetch request.
For the second option, that's also pretty easy. You take the predicate from your first request and AND it with your new predicate:
NSPredicate *original = ...;
NSPredicate *newCondition = ...;
NSPredicate *newFilter = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:original, newCondition, nil]];
Personally, I usually find the first option to be simpler overall.
From the docs:
To summarize, though, if you execute a
fetch directly, you should typically
not add Objective-C-based predicates
or sort descriptors to the fetch
request. Instead you should apply
these to the results of the fetch. If
you use an array controller, you may
need to subclass NSArrayController so
you can have it not pass the sort
descriptors to the persistent store
and instead do the sorting after your
data has been fetched.
I don't get it. What's wrong with using them on fetch requests? Isn't it stupid to get back a whole big bunch of managed objects just to pick out a 1% of them in memory, leaving 99% garbage floating around? Isn't it much better to only fetch from the persistent store what you really need, in the order you need it? Probably I did get that wrong...
The documentation refers to Objective-C-based predicates or sort descriptors. This is NOT the same thing as a standard predicate or sort descriptor you see in the example available in the same page of the documentation you are quoting.
For instance, using
+ (NSPredicate *)predicateWithBlock:(BOOL (^)(id evaluatedObject, NSDictionary *bindings))block;
to build a predicate allows you using Objective-C to implement the block used to select the objects. Since the complexity of the block may be arbitrarily high, in this case Apple recommends to first fetch all of the objects, then to apply these filters.
I'm performing a search of a large plist file which contains dictionaries, tens of thousands of them, each with 2 key/string pairs. My search algorithms goes through the dictionaries, and when it finds a text match in either of the strings in the dictionary, the contents of the dictionary are inserted. Here is how it works:
NSDictionary *eachEntry;
NSArray *rawGlossaryArray = [[NSArray alloc] initWithContentsOfFile:thePath]; // this contains the contents of the plist
for (eachEntry in rawGlossaryArray)
{
GlossaryEntry *anEntry = [[GlossaryEntry alloc] initWithDictionary:eachEntry];
NSRange titleResultsRange = [anEntry.title rangeOfString:filterString options:NSCaseInsensitiveSearch];
NSRange defResultsRange = [anEntry.definition rangeOfString:filterString options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0 || defResultsRange.length > 0) {
// store that item in the glossary dictionary with the name as the key
[glossaryDictionary setObject:anEntry forKey:anEntry.title];
}
[anEntry release];
}
Each time a search is performed, there is a delay of around 3-4 seconds in my iPhone app (on the device at least; everything runs pretty quickly in the simulator). Can anyone advise on how I might optimize this search?
Without looking at the data set I can't be sure, but if you profile it you are spending the vast percentage of your time in -rangeOfString:options:. If that is the case you will not be able to improve performance without fundamentally changing the data structure you are using to store your data.
You might want to construct some sort trie with strings and substrings pointing to the objects. It is much more complicated thing to setup, and insertions into it will be more expensive, but lookup would be very fast. Given that you are serializing out the structure anyway expensive inserts should not be much of an issue.
That just cries out for using a database, that you pre-populate and put into the application.
A few suggestions:
You're doing a lot of allocing and releasing in that loop. Could you create a single GlossaryEntry before the loop, then just reload it's contents inside the loop? This would avoid a bunch of alloc/releases.
Rather than loading the file each time, could you lazy load it once and keep it cached in memory (maybe in a singleton type object)? Generally this isn't a good idea on the iPhone, but you could have some code in your "didReceiveMemoryWarning" handler that would free the cache if it became an issue.
You should run your application is Instruments, and see what the bottleneck really is. Performance optimizations in the blind are really difficult, and we have tools to make them clear, and the tools are good too!
There's also the possibility that this isn't optimizable. I'm not sure if it's actually hanging the UI in your app or just taking a long time. If it's blocking the UI you need to get out of the main thread to do this work. Same with any significant work to keep an app responsive.
try the following, and see if you get any improvement:
1) use
- (NSRange)rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
and as mask, pass the value NSLiteralSearch. This may speedup search considerably as described in the Apple documentation (String Programming Guide for Cocoa):
NSLiteralSearch Performs a byte-for-byte comparison. Differing literal sequences (such as composed character sequences) that would otherwise be considered equivalent are considered not to match. Using this option can speed some operations dramatically.
2) From the documentation (String Programming Guide for Cocoa):
If you simply want to determine whether a string contains a given pattern, you can use a predicate:
BOOL match = [myPredicate evaluateWithObject:myString];
For more about predicates, see Predicate Programming Guide.
You're probably getting the best performance you're likely to get, given your current data structures. You need to change how you're accessing the data, in order to get better performance.
Suggestions, in no particular order:
Don't create your GlossaryEntry objects in a loop while you're filtering them. Rather than storing the data in a Property List, just archive your array of GlossaryEntry objects. See the NSCoding documentation.
Rather than searching through tens of thousands of strings at every keystroke, generate an index of common substrings (maybe 2 or 3 letters), and create an NSDictionary that maps from that common substring to the set of results to use as an index. You can create the index at build time, rather than at run-time. If you can slice up your data set into several smaller pieces, the linear search for matching strings will be considerably faster.
Store your data in an SQLite database, and use SQL to query it - probably overkill for just this problem, but allows for more sophisticated searches in the future, if you'll need them.
If creating a simple index doesn't work well enough, you'll need to create a search tree style data structure.
You should profile it in instruments to find where the bottleneck actually is. If I had to guess, I would say the bottleneck would be [[NSArray alloc] initWithContentsOfFile:thePath].
Having said that, you'd probably get the best performance by storing the data in an sqlite database (which you would search with SQL) instead of using a plist.