I've got an NSTableViewDataSource/...Delegate backed by an array in my controller. Now, from time to time I'm going to update the array, but I'd like to make sure this doesn't happen while the UI is possibly refreshing what's displayed.
The trivial part is locking the list itself, so it doesn't get change while drawing each cell. But how do I lock it for the whole update cycle? (i.e. from getting the number of rows to finishing the current screen draw) Are there any pre/post update hooks I can use, or are there better ways to approach it?
Related
I am attempting to run a database fetch process in the background without locking the user interface.
Currently I have a button that does this, but I would like it to be automatic so that it can get more results as user is browsing current results.
Here is the code that the button does, I would like to make this automatic and not lock the UI. Also if there is a way to pause the process, but continue where it left off if user goes to another screen that would also be very useful.
Thanks in advance!
-(IBAction)continueUpdatingResultsButtonPressed:(UIButton*)sender{
[findMoreButton removeFromSuperview];
[self continueFindingMoreRecipes]; //(do this in background without locking screen)
[self loadRefreshButton];//At completion load this button (a blinking button) to refresh the cells with new results
}
A typical pattern you can use is something like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// perform data processing here (done in the background)
dispatch_async(dispatch_get_main_queue(), ^{
// update user interface here (done on the main thread)
});
});
You could do batch requests where you cache the next X amount of answers every time your UI got with in Y of the current end. Depending on what you are using a lot of databases have protocols that can help you batch cache easily. Good luck!
Use grand central dispatch. Create a new queue, dispatch it with a block and when you need to update, call dispatch get main queue. There is no way to pause this once the queue has been dispatched though. Maybe load recipes into intermediary then update as needed.
Look for some gcd tutorials there are a few decent ones there.
Would give you more code but I'm typing on iPhone.
It strikes me (especially since you are, by your own admission, "very new to programming") that it might not be prudent to pursue GCD to prefetch data in a background queue, make sure you coordinate the background queue's database operations with the foreground's database operations (possibly via something like FMDB's FMDatabaseQueue or something equivalent), gracefully handle pausing this operation as you go to other screens (as you indicated in your question) and making sure you don't cause retain cycles in the process.
To make matters worse, I gather that this is all in pursuit of a possibly questionable goal, if I understand you correctly, to retrieve 10,000 recipes in the background. Don't get me wrong. You certainly can design all of the background operations like we've outlined, but I think you should stop and ask yourself whether that's the right design for your business problem.
I might suggest an infinitely easier solution. Just load your tableview with the first x recipes, and as the user scrolls down, when you start to approach the end of the tableview, detect that fact and retrieve the next x records and add them to the tableview. But any user interface that is expecting the user to flip through 10,000 entries doesn't pass the smell test. When I think of a database with 10,000 entries, I think of something more like a imdb/wikipedia/google/facebook-like user interface rather than a contacts-style user interface.
Regardless, you almost certainly don't want your app just endlessly retrieving recipes in the background. You can solve your UI performance issue, but maybe replace it with memory management issues. And you're going to design a complicated system architecture when it's not entirely clear whether your recipe app requires that.
I have implemented a client for a paginated REST service where I populate the whole table with empty entries and then load them in the background using pagination when the user starts scrolling the table.
This seems to work very well except for a little detail: I am calling reloadRowsAtIndexPaths: in the main UI thread (because UIKit requires so), and I feel the animation sometimes makes me lose input touches.
This is, the user starts scrolling through the list and items start to load. Sometimes a reload animation happens at the same time the user is just touching the screen again, and this touch is not recognized. The scrolling then doesn't continue and stops. It doesn't happen all the time, and I guess it is an infrequent user case (the user is expected to read each row of results before scrolling down) but it annoys me to no end.
I'm doing most of my animations with blocks and the flag UIViewAnimationOptionAllowUserInteraction is really helpful, so is there a block version of reloadRowsAtIndexPaths where the reload animation would not block the user interaction with the scrolling?
I think the solution you seek is to background-load your data in a thread (as you describe) and only call reloadRowsAtIndexPaths: once the data is received and ready to display. You should also probably redisplay the data NOT animated.
I don't think there's anything you can do to get around the missed touches with your current scheme. My suggestion is to "do what iOS wants" rather than "try to cajole iOS to do what you want." Yes, probably not the answer you wanted to hear, but I think that's just the way it works.
(Btw, you can always use bugreporter.apple.com to make an enhancement request! :)
Deleting or moving rows for a UITableView that is backed with local data (e.g., NSArray) is easy and instantaneous:
Remove the value from the array.
Call deleteRowsAtIndexPaths:withRowAnimation:.
Profit!
But my table view communicates with a web service, which means once the "Delete" button on that row gets tapped, I have to forward a request on to the server (via ASIHTTPRequest, of course), get the response, and then tell the table view to run its little delete-row animation, all with a few seconds of latency in between.
From a high-level, what's the best way to do that? Throw some callback selector into ASIHTTPRequest's userInfo dictionary? KVO?
Bonus points for some nice UI touch, like some kind of spinner on the soon-to-be-deleted cell.
The most elegant way I know of is to use Core Data for the local data, and to have your UITableView listening for change notifications from the Core Data store. This maintains model/view separation, and yet you can still get the eye candy of a row-deletion animation. It goes like this:
User says to delete a row.
Your code sends off an ASIHTTPRequest, and registers a selector to be called back when the request succeeds.
When it's done, the callback selector modifies the model that is in your Core Data store.
This automatically causes your UITableView to be notified that a row was deleted, so it can animate the deletion of the row.
This doesn't get the bonus points, because it doesn't give you any sort of UI indication that the cell will be deleted soon. One thing I've considered doing sometimes, but haven't been brave enough to try, is to optimistically code things on the assumption that the web-service call will almost certainly succeed, so go ahead and delete the row immediately, before the ASIHTTPRequest indicates success/failure; but then, if it does fail, roll back, and make the row re-appear. This has the advantage of making the app much faster in the common case where the web-service call succeeds. Core Data gives you a couple of ways to do this kind of "roll-back" stuff, but still, it definitely gets tricky, so it may not be worth it.
If you don't want to use Core Data, then to me KVO is the second-best solution.
EDIT: Thinking about it a bit more, in order to get a visual indicator that the row is about to be deleted, your Core Data model could have a flag on each row, "markedForDeletion" or something; when you fire off the ASIHTTPRequest, you would also modify the model to set markedForDeletion to true. The UITableView would be notified of the change (because it has registered for notifications); so it would then do whatever UI you want on top of the row, e.g. a spinner or something, to indicate that it's being deleted. Then, if the ASIHTTPRequest succeeds, it just deletes the row; but if it fails, it sets the rows "markedForDeletion" flag back to false, which causes the UITableView to turn off the spinner.
I have a horizontally scrolling UIScrollview with paging enabled. Each page represents a data feed. Each data feed consumes a fairly large amount of memory including text and images displayed in a UITableView. Since the user can have an unlimited amount of data feeds, I need to lazy load them to prevent maxing out my memory usage. My thought is to keep up to 5 data feeds in memory at any given point, and release anything outside of that range. My initial take is to keep the page in the viewport in memory, and the 2 pages to either side of it. This way when the user scrolls, the next sequential page will always be in memory and will display quickly.
Here is my problem:
We also need to support a scenario where a user can skip to a specific data feed, possibly 10 or more pages to the right or left, which throws my entire lazy loading scheme out the window.
Might there be a better strategy to support this scenario?
Yes, what you can do is create an outer scroll view, which houses individual cells akin to a tableview. In this respect, the cells have a content view which you can place your data, let's just assume you know how to do that since it seems you do.
Once you have this architecture in your mind, it becomes fairly clear: You can, knowing the width of your cells, and the size of the screen, some simple math can tell you how many you have on screen, and you can add one to the left or right so you're preloading some data for when the user scrolls.
This will say, give you the ability to have in memory, at most 5 feeds, if 3 are visible, at the start or end of the content view in the scrollview, 4 feeds, regardless of whether or not you have a billion feeds.
One critical part of this is cell reuse. You maintain a couple NSSets, one for recycled cells, and one for visible cells. Add items that have gone off screen to the recycled cells, dequeue items from recycled cells when setting up the cell, as to save additional memory allocations, which can be expensive. Just remember, using this strategy, you are still subjective to the same caveats as a UITableView with respect to cell reuse.
I'm plugging some software I wrote here, so forgive me for that, but I'm doing so as an example of what I'm talking about if you get stuck implementing what I discussed here, it's available here for your perusal.
One final note. To support skipping of cells, it's just simple math again to adjust the point in the scrollview you are at. The action for this can be done with a gesture, though now we're talking a pan gesture recognizer, with some specific properties that will be specific to your application, as an example. Or you can use buttons if you really must. Just ensure you know how to calculate your offsets to your cells, and scroll to that point. You'll be fine.
It's hard to give accurate advice with the information provided in the question. So I will just present a few thoughts I got when reading the question.
Does it take long to download a feed? Would it be possible to just download a few item (a screenful) to get the first few items showing right away? Perhaps lazy load the images if possible.
Have you considered caching the feed data on disk? That way you can present some data right away and then update the feed as new data gets downloaded.
Since each page is a feed view, would the user just scroll past a feed without looking at it? Do you really need to load 2 views on each side or can you get away with just 1 view on each side.
I don't think your lazy loading scheme stops working just because the user can skip directly to any page. You would have to start loading the data for that page when it is selected but by using a disk cache or downloading a small sample could make the app feel faster. I also think that using some kind of animation to animate to the selected page could buy you a little time.
Here is my problem: We also need to support a scenario where a user can skip to a specific data feed, possibly 10 or more pages to the right or left, which throws my entire lazy loading scheme out the window.
Then you need to fix your data structure. I wrote pretty much exactly this (a UITableView-like paging scroll view) and it works fine (there are some reloading quirks, but hey...).
Keep track of which pages you've loaded. I used a ring-buffer-alike modulo 8 and spent a while getting the code right; it's probably a lot easier to just use an NSDictionary with NSNumber keys and UIView values. This means when you change from page 1 to 10, you can still tell that the loaded views are for pages 1, 2, and 3, and drop them.
Load the required pages in -layoutSubviews. I would load 1 or 3; 5 is probably too many (but you need to load at least 2 if you're between pages).
Load 3 (one to either side) in -scrollViewDidScroll:. This is so that when you scroll from page 1 to 2, it doesn't try to load page 4 (which hasn't been loaded yet).
Load 5 (two to either side) in –scrollViewDidEndDragging:willDecelerate: if willDecelerate is NO, –scrollViewDidEndDecelerating:, –scrollViewDidScrollToTop:, and –scrollViewDidEndScrollingAnimation:. The idea is that the animation's over, so you can load the extra views without the user perceiving lag.
Possibly load 5 in –scrollViewWillBeginDragging:, to make sure that page 3 is loaded if you're currently on page 1.
I decided to do "two pages either side" because when you flick from page 1 to page 2, it often shows a pixel-wide sliver of page 3 when it bounces. This can be avoided with scroll view insets, but we didn't think of that at the time (oops). There's otherwise not that much of a reason to choose 5 over 3.
It's a bit of work to get right, but otherwise seems to work flawlessly.
I am developing an iOS application and am having some issues deciding how to approach a problem.
I am using two UITableViewControllers to display different views of the same data. One is a master list, and the other only contains items which are marked as "favourite". Also the items are variable height, so I am using "heightForRowAtIndexPath" to indicate the height for each item. The problem is speed, when I switch from one view to another, it needs to be updated to display the changes made in the other (marked favourite/unfavourite).
Solution #1:
Reload the data each time a table view becomes visible. This does not work nicely because although the data is display using lazy loading, the "heightForRowAtIndexPath" is called for every item before ANY data is loaded, and its slow. on my iPhone 4 a list of about 300 items takes about four seconds to load, even if the height values are cached (the bottleneck is applying the height, not retrieving it).
Solution #2:
Manually manipulate the tables when changes are made. I have not tried this, but it would likely be buggy. Your thoughts?
Solution #3:
Using a notification type system to notify the other table of updates to items that might currently be loaded. I have not tried this, because it seems over the top and might not work at all.
Does anyone know of an easy way to show two views of the same data?
You can reload n rows with reloadRowsAtIndexPaths:withRowAnimation. I never did it, but I think it's there because it's faster, so you might want to try it out.
On the heightForRow: thingy, I can remember reading in the Apple docs that that function is indeed a killer for performance. Perhaps you could take the maximum height of the rows, and set that in the UITableView.rowHeight?