I'm trying to speed up my app search , it get lags when there is a lot of data.
so i'm trying to split search Predicate on UI by using dispatch_async not dispatch_sync cause no different if I use it.
The problem is when i use dispatch_async, the app crash sometimes because [__NSArrayI objectAtIndex:]: index "17" beyond bounds.
I now this happened because lets say the first one still work and reload the tableView and continue search will change the array size depend on result so in this case "CRASH" :(
this is my code:
dispatch_async(myQueue, ^{
searchArray = [PublicMeathods searchInArray:searchText array:allData];
} );
if(currentViewStyle==listViewStyle){
[mytable reloadData];
}
and i've tried this :
dispatch_async(myQueue, ^{
NSArray *tmpArray = [PublicMeathods searchInArray:searchText array:allData];
dispatch_sync(dispatch_get_main_queue(), ^{
searchArray = tmpArray;
[mytable reloadData];
});
});
but in this case the lags still there.
Update -1- :
The search Predicate takes just 2ms :) after hard work :)
but the keyboard still lags when the user searches, so the only thing I do after get result is reload table "change in UI" this what I think make it lags,
So what I search for split this two operation "typing on keyboard & refresh UI".
Update -2- :
#matehat https://stackoverflow.com/a/16879900/1658442
and
#TomSwift https://stackoverflow.com/a/16866049/1658442
answers work like a charm :)
If searchArray is the array that is used as table view data source then this array must
only be accessed and modified on the main thread.
Therefore, on the background thread, you should filter into a separate temporary array first. Then you assign the temporary array to searchArray on the main thread:
dispatch_async(myQueue, ^{
NSArray *tmpArray = [PublicMeathods searchInArray:searchText array:allData];
dispatch_sync(dispatch_get_main_queue(), ^{
searchArray = tmpArray;
[mytable reloadData];
});
});
Update: Using a temporary array should solve the crash problem, and using a background thread helps to keep the UI responsive during the search. But as it turned out in the discussion, a major reason for the slow search might be the complicated search logic.
It might help to store additional "normalized" data (e.g. all converted to lower-case, phone numbers converted to a standard form, etc ...) so that the actual search can be done with
faster case-insensitive comparisons.
One solution might be to voluntarily induce a delay between searches to let the user type and let the search be performed asynchronously. Here's how:
First make sure your queue is created like this :
dispatch_queue_t myQueue = dispatch_queue_create("com.queue.my", DISPATCH_QUEUE_CONCURRENT);
Have this ivar defined in your class (and set it to FALSE upon initialization):
BOOL _scheduledSearch;
Write down this macro at the top of your file (or anywhere really, just make sure its visible)
#define SEARCH_DELAY_IN_MS 100
And instead of your second snippet, call this method:
[self scheduleSearch];
Whose implementation is:
- (void) scheduleSearch {
if (_scheduledSearch) return;
_scheduledSearch = YES;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)((double)SEARCH_DELAY_IN_MS * NSEC_PER_MSEC));
dispatch_after(popTime, myQueue, ^(void){
_scheduledSearch = NO;
NSString *searchText = [self textToSearchFor];
NSArray *tmpArray = [PublicMeathods searchInArray:searchText array:allData];
dispatch_async(dispatch_get_main_queue(), ^{
searchArray = tmpArray;
[mytable reloadData];
});
if (![[self textToSearchFor] isEqualToString:searchText])
[self scheduleSearch];
});
}
[self textToSearchFor] is where you should get the actual search text from.
Here's what it does :
The first time a request comes in, it sets the _scheduledSearch ivar to TRUE and tells GCD to schedule a search in 100 ms
Meanwhile any new search requests is not taken care of, because a search is going to happen anyway in a few ms
When the scheduled search happens, the _scheduledSearch ivar is reset to FALSE, so the next request is handled.
You can play with different values for SEARCH_DELAY_IN_MS to make it suit your needs. This solution should completely decouple keyboard events with workload generated from the search.
First, a couple notes on the code you presented:
1) It looks as if you're likely queuing up multiple searches as the user types, and these all have to run to completion before the relevant one (the most recent one) updates the display with the desired result set.
2) The second snippet you show is the correct pattern in terms of thread safety. The first snippet updates the UI before the search completes. Likely your crash happens with the first snippet because the background thread is updating the searchArray when the main thread is reading from it, meaning that your datasource (backed by searchArray) is in an inconsistent state.
You don't say if you're using a UISearchDisplayController or not, and it really doesn't matter. But if you are, one common issue is not implementing - (BOOL) searchDisplayController: (UISearchDisplayController *) controller shouldReloadTableForSearchString: (NSString *) filter and returning NO. By implementing this method and returning NO you are turning off the default behavior of reloading the tableView with each change to the search term. Instead you have opportunity to kick off your asynchronous search for the new term, and update the UI ([tableview reloadData]) only once you have new results.
Regardless of whether you're using UISearchDisplayController you need to take a few things into consideration when implementing your asynchronous search:
1) Ideally you can interrupt a search-in-progress and cancel it if the search is no longer useful (e.g. the search term changed). Your 'searchInArray' method doesn't appear to support this. But it's easy to do if your just scanning an array.
1a) If you can't cancel your search, you still need a way at the end of the search to see if your results are relevant or not. If not, then don't update the UI.
2) The search should run on a background thread as to not bog down the main thread and UI.
3) Once the search completes it needs to update the UI (and the UI's datasource) on the main thread.
I put together sample project (here, on Github) that performs a pretty inefficient search against a large list of words. The UI remains responsive as the user types in their term, and the spawned searches cancel themselves as they become irrelevant. The meat of the sample is this code:
- (BOOL) searchDisplayController: (UISearchDisplayController *) controller
shouldReloadTableForSearchString: (NSString *) filter
{
// we'll key off the _currentFilter to know if the search should proceed
#synchronized (self)
{
_currentFilter = [filter copy];
}
dispatch_async( _workQueue, ^{
NSDate* start = [NSDate date];
// quit before we even begin?
if ( ![self isCurrentFilter: filter] )
return;
// we're going to search, so show the indicator (may already be showing)
[_activityIndicatorView performSelectorOnMainThread: #selector( startAnimating )
withObject: nil
waitUntilDone: NO];
NSMutableArray* filteredWords = [NSMutableArray arrayWithCapacity: _allWords.count];
// only using a NSPredicate here because of the SO question...
NSPredicate* p = [NSPredicate predicateWithFormat: #"SELF CONTAINS[cd] %#", filter];
// this is a slow search... scan every word using the predicate!
[_allWords enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
// check if we need to bail every so often:
if ( idx % 100 == 0 )
{
*stop = ![self isCurrentFilter: filter];
if (*stop)
{
NSTimeInterval ti = [start timeIntervalSinceNow];
NSLog( #"interrupted search after %.4lf seconds", -ti);
return;
}
}
// check for a match
if ( [p evaluateWithObject: obj] )
{
[filteredWords addObject: obj];
}
}];
// all done - if we're still current then update the UI
if ( [self isCurrentFilter: filter] )
{
NSTimeInterval ti = [start timeIntervalSinceNow];
NSLog( #"completed search in %.4lf seconds.", -ti);
dispatch_sync( dispatch_get_main_queue(), ^{
_filteredWords = filteredWords;
[controller.searchResultsTableView reloadData];
[_activityIndicatorView stopAnimating];
});
}
});
return FALSE;
}
- (BOOL) isCurrentFilter: (NSString*) filter
{
#synchronized (self)
{
// are we current at this point?
BOOL current = [_currentFilter isEqualToString: filter];
return current;
}
}
i believe your crash is indeed solved by the embedding of the display of the UI element for which searchArray is the backing element in a call to GrandCentralDispatch inside of the other call (as you show in your updated original post). that is the only way to make sure you are not causing the elements of the array to change behind the scenes while the display of the items associated with it is taking place.
however, i believe if you are seeing lag, it is not so much caused by the processing of the array at 2ms or the reload that takes 30ms, but rather by the time it takes GCD to get to the internal dispatch_sync call on the main queue.
if, by this point, you have managed to get the processing of your array down to only 2ms in the worst case (or even if you've managed to get it down to less than 30ms, which is about the time it takes to process a frame in the main run loop at 30 fps), then you should consider abandoning GCD altogether in your effort to process this array. taking 2ms on the main queue to process your array is not going to cause any buggy behavior.
you may have lag elsewhere (i.e. if you are incrementing search results by trying to go out to the net to get the results, you may want to do the call and then process the response on your separate dispatch queue), but for the times you are talking about, this bit of processing doesn't need to be split out onto separate queues. for any hard-core processing that takes over 30ms, you should consider GCD.
I suspect your problem is that allData is shared between the main queue and the background queue. If you make a change in allData on the main queue, that may shorten allData in the background queue, causing an index that used to be valid to become invalid.
It's also possible that the problem is not allData itself, but some array within the objects in allData. Try setting a breakpoint on exceptions (in Xcode, open the Breakpoints source list, click the plus button at the bottom, and choose "Add Exception Breakpoint...") so you can see exactly where the error occurs.
In either case, you have two possible solutions:
Copy the offending object before using it in the search. This protects the background queue from changes in the main queue, but depending on what you need to copy, it may be difficult to get the changes back into the UI—you might have to match the copies back to their originals.
Use a lock (like #synchronized) or a per-object queue to ensure only one queue is using the object at a time. NSManagedObjectContext uses the latter approach for its -performBlock: and -performBlockAndWait: methods. It may be a little tricky to do this without blocking the main queue, though.
Try to modify your functions the next way:
function prototype;
- (void)searchInArray:searchText array:allData complete: (void (^)(NSArray *arr)) complete;
function itself
- (void)searchInArray:searchText array:allData complete: (void (^)(NSArray *arr)) complete {
NSArray * array = [NSArray new];
// function code
complete(array)//alarming that we have done our stuff
}
and when you are calling this function
dispatch_queue_t searchQueue = dispatch_queue_create("com.search",NULL);
dispatch_async(searchQueue,^{
[PublicMeathods searchInArray:searchText array:allData complete:^(NSArray *arr) {
searchArray = arr;
dispatch_async(dispatch_get_main_queue(), ^{
[myTable reloadData];
});
}];
});
Hope it will help you)
I found a simple solution with the same spirit of the solution presented by Matehad (wait some time and perform a search only if the user doesn't input anything else). Here it is:
Declare 2 global counters and a global string:
int keyboardInterruptionCounter1 = 0, int keyboardInterruptionCounter2 = 0 and NSString *searchTextGlobal
On the searchBar function do this:
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
keyboardInterruptionCounter1++;
searchTextGlobal = searchText;//from local variable to global variable
NSTimeInterval waitingTimeInSec = 1;//waiting time according to typing speed.
//waits for the waiting time
[NSTimer scheduledTimerWithTimeInterval:waitingTimeInSec target:self selector:#selector(timerSearchBar:) userInfo:nil repeats:NO];
}
-(void)timerSearchBar:(NSTimer *)timer{
keyboardInterruptionCounter2++;
// enters only if nothing else has been typed.
if (keyboardInterruptionCounter2 == keyboardInterruptionCounter1) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
(unsigned long)NULL), ^(void) {
//do the search with searchTextGlobal string
dispatch_async(dispatch_get_main_queue(), ^{
//update UI
});
});
}
}
Explanation: The search is performed only if both counters are the same, this only happens if the user has typed and waited .52 sec without typing anything else. Instead, if the users types fast enough, then no query is done. The solution can be done with or without threading.
Martin R has posted a correct answer. The only thing to point out that instead of
dispatch_sync(dispatch_get_main_queue()
it should be
dispatch_async(dispatch_get_main_queue()
The complete code in Swift would be:
let remindersFetcherQueue = dispatch_queue_create("com.gmail.hillprincesoftware.remindersplus", DISPATCH_QUEUE_CONCURRENT)
dispatch_sync(remindersFetcherQueue) {
println("Start background queue")
estore.fetchRemindersMatchingPredicate(remindersPredicate) {
reminders in
// var list = ... Do something here with the fetched reminders.
dispatch_async(dispatch_get_main_queue()) {
self.list = list // Assign to a class property
self.sendChangedNotification() // This should send a notification which calls a function to ultimately call setupUI() in your view controller to do all the UI displaying and tableView.reloadData().
}
}
}
I am using Core Data however haven't done any complex queries and am completely lost - come from SQL background so need help creating a NSPredicate.
My question
I need to retrieve a list of Perspective's (with unique name) which in-directly belong to a specific EntityManagedObject.
Overview of the database
As you can see EntityManagedObject can have many EntityManagedObjects and can have many ObjectiveManagedObject's.
EntityManagedObject therefore has a single EntityManagedObject as a parent, and ObjectiveManagedObjective has a single EntityManagedObject as a parent.
ObjectiveManagedObject has one Perspective. A Perspective can belong to many ObjectiveManagedObjects.
make a method,
-(NSArray *) getEntityManagedObjectsWithParentEntity:(EntityManagedObject *) parentObject;
another method,
-(NSArray *) getObjectiveManagedObjectsWithEntityManagedObjects:(NSArray *) entityManagedObjects;
then ,
-(NSArray *) getPerspectivesWithEntityManagedObject:(EntityManagedObject *) entityObject
{
NSArray *objectiveManagedObjects = [self getObjectiveManagedObjectsWithEntityManagedObjects: [self getEntityManagedObjectsWithParentEntity:entityObject] ];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"Objectives IN %#", objectiveManagedObjects];
}
I'm searching for a better alternative to deal with this problem.
In a CoreData model I have an NSManagedObject called Project. In its subclass I override the accessor method (setter) for its label attribute. Here I check whether the same label is already used. If it is, I add an underscore and a number to the label, e.g. "MyProject" is renamed to "MyProject_1". Of course I also have to check whether I find the label "MyProject" or "MyProject_"+number. I do that with a Regular Expression.
NSString *regexString = [NSString stringWithFormat:#"%#_[0-9]+", value];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"(label = %#) OR (label MATCHES %#)", value, regexString];
[request setPredicate:predicate];
Then I check how many results are fetched, lets say 5, so I know that the next one hast to be called "MyProject_6".
It works fine but you probably have already noticed that there is a little problem with this code: What happens if I have the following labels:
MyProject_1, MyProject_2, MyProject_3
and the user decides to call a project MyProject_55.
Then my search would retrieve 4 elements and the next project would be labeled MyProject_5 instead of MyProject_4. And what it's worse, at some point, I would end up having two MyProject_55. I know it's unlikely to happen, but it can :).
Any ideas for something better?
Here's the accessor method
#pragma mark - Setter for label
- (void)setLabel:(NSString *)aLabel
{
if ([[self primitiveValueForKey:#"label"] isEqualToString:aLabel])
{
return;
}
NSMutableArray *objects = [self fetchObjectsWithValueEqualTo:aLabel];
NSUInteger objectsCount = [objects count];
aLabel = objectsCount > 0 ? [NSString stringWithFormat:#"%#_%d",aLabel, objectsCount] : aLabel;
[self willChangeValueForKey:#"label"];
[self setPrimitiveValue:aLabel forKey:#"label"];
[self didChangeValueForKey:#"label"];
}
Its a little expensive but the simplest way out of this dilemma is once you have a new label decision "MyLabel_4" recheck if that label exists in the store.
Rinse and repeat until you really have a unique label. Core Data is very efficient so this isnt going to matter in a userland case.
I have a UISegmentControl with my UITableView that sorts the data. I'd like to be able to do things:
(1) default sort (so when the user turns on the app for the first time, it would select the first segment, and sort by that action)
(2) remember where the user was between table loads. What I mean by this is, similar to Apple's coverflow, when I go to a different cover, the UITableView repopulates. So if the last time the user was there, the sort was on the 3rd segment, then it would remember that.
I'm a bit new to object-oriented design, and this was my best guess to not have the same redundant code everywhere: (MarkersList is a NSMutableArray)
- (NSArray *)sortByName:(NSArray *)sortDescriptors {
return [self.MarkersList sortedArrayUsingDescriptors:sortDescriptors];
}
- (NSArray *)sortByRSID:(NSArray *)sortDescriptors {
return [self.MarkersList sortedArrayUsingDescriptors:sortDescriptors];
}
- (void)setSortedMarkersList:(NSArray *)sortedArray {
if (self.MarkersList != nil) {
[self.MarkersList removeAllObjects];
}
[self.MarkersList addObjectsFromArray:sortedArray];
}
- (IBAction)sortButtonPressed:(UISegmentedControl *)segmentControl {
// Create sort descriptors
NSSortDescriptor *nameDescriptor = [[[NSSortDescriptor alloc] initWithKey:#"Name" ascending:YES selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSSortDescriptor *rsID = [[NSSortDescriptor alloc] initWithKey:#"ID" ascending:YES];
if ([segmentControl selectedSegmentIndex] == NAME) { // this is #define 0
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:nameDescriptor, rsIDDescriptor, nil];
NSArray *sortedArray = [self sortByGene:sortDescriptors];
[self setSortedMarkersList:sortedArray];
[sortDescriptors release];
}
else if ([segmentControl selectedSegmentIndex] == RS_ID) {
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:rsIDDescriptor, resultDescriptor, nameDescriptor, nil];
NSArray *sortedArray = [self sortByRSID:sortDescriptors];
[sortDescriptors release];
[self setSortedMarkersList:sortedArray];
}
[self.MarkersTableView reloadData];
}
I haven't implemented the third sort yet since it's not just an NSString or NSNumber like the other two yet. So far, I think it works correctly. However, the problem I have is to implement (1), I would need to call sortByName when my table is loaded. I could just create the NSSortDescriptors again, but that seems redundant. Is there a more OOD way to achieve this?
For (2), I'm guessing I could save that index for the table in a dictionary, and retrieve it when that table is loaded. Or something along those lines, not really sure.
Any help is greatly appreciated. Thanks!
This isn't so much an OO question, as iOS doesn't always let us use best practices to solve a problem. The best bet for your situation, I think, is to store the information on the selected sort in the NSUserDefaults. In your -viewDidLoad method, check if the selected sort object exists in NSUserDefaults, use it if it does, and if not choose a reasonable default value.
Don't worry about creating NSSortDescriptors with each load of the application, unless you have done profiling and determined that a large amount of time is spent building it. Serializing and deserializing the NSSortDescriptors would be far more inefficient than just recreating it when needed. Apple spends a lot of time optimizing frequently used classes like NSSortDescriptor.
Regarding #2, you can use indexPathsOfVisibleRows on the UITableView to get an array of visible indices, store the first one in UserDefaults, then on load (or pop from the next view controller if that occurs) call –scrollToRowAtIndexPath:atScrollPosition:animated:.
Once you're code is functioning, I recommend you watch the various videos on iTunes U regarding profiling and Instruments. It's a wonderful tool that is often overlooked, and really helps concentrate effort where it's needed.
Much of my code is based off of Apple's TableSearch example, however my app contains 35,000 cells that need to be searched rather than the few in the example. There isn't much documentation online about UISearchDisplayController since it is relatively new. The code I am using is as follows:
- (void)filterContentForSearchText:(NSString*)searchText {
/*
Update the filtered array based on the search text and scope.
*/
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
/*
Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
*/
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
for (Entry *entry in appDelegate.entries)
{
if (appDelegate.searchEnglish == NO) {
NSComparisonResult result = [entry.gurmukhiEntry compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredListContent addObject:entry];
}
}
else {
NSRange range = [entry.englishEntry rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(range.location != NSNotFound)
{
[self.filteredListContent addObject:entry];
}
}
}}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString];
[self.view bringSubviewToFront:keyboardView];
// Return YES to cause the search result table view to be reloaded.
return YES;}
My problem is that there is a bit of a delay after each button is pressed on the keyboard. This becomes a usability issue because the user has to wait after typing in each character as the App searches through the array for matching results. How can this code be adjusted so that the user can continually type without any delays. In this case, it is ok for a delay in the time it takes for the data to reload, but it should not hold up the keyboard in typing.
Update:
One way to acccomplish searchching while typing without "locking up" the UI, is to use threads.
So you can call the the method that performs the sorting with this method:
- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg
Which will keep it out of the main thread, allowing the UI update.
You will have to create and drain your own Autorealease pool on the background thread.
However, when you want to update the table you will have to message back to the main thread (all UI updates MUST be on the main thread):
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
You could also get a little more control by using NSOperation/NSOperationQueue Or NSThread.
Note that implementing threads is fraught with peril. You will have to make sure your code is thread-safe and you may get unpredictable results.
Also, here are other stackoverflow answers that may help:
Using NSThreads in Cocoa?
Where can I find a good tutorial on iPhone/Objective-C multithreading?
Original answer:
Don't perform the search until the user presses the "search" button.
There is a delegate method you can implement to catch the pressing of the search button:
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar;