UIView/CALayer bulk loading to improve rendering - ios

I have a view that has many subviews and sublayers that are built up from a background thread using NSOperation. Then I invoked back to the main thread when adding them to the UIView that is already being displayed. When everything is done rendering, performance and responsiveness is great. However, the main thread seems to be taking a very long time to do the initial render of my views, causing performance issues while the initial render is taking place.
I was able to get around this performance issue if my NSOperation added the subviews/sublayers to a currently visible UIView, but it would not appear until it was tapped on. Calling the setNeedsDisplay method did not resolve this issue.
I am wondering if their is a way to tell the main thread that I am adding a bunch of views so that it knows to do this more optimally? Somthing similar to an addSubviewRange instead of addSubview?

Related

Prepare UIImage with lots of layers on background thread

I have the problem that I have some really big UIScrollView and tons of images loaded on it as user scrolls. Images are stored on the device, however I receive information from server what to display on particular part of UIScrollView. When user scrolls a bit I need to show images at new position as I cannot afford to draw whole UIScrollView with images at startup. For the background I had one relatively small image which I move throughout the View. But the problem is that on top of that background I should draw a lot of UIImage objects(about 300-400) which are not particulary bih however are separeted on layers(one image on top of other on top of other etc.). Blocking scrolling while drawing is NOT an option.
Now I'm trying to decide which approach will suite my best:
Add all needed images to UIView on background thread and then just add UIView to ScrollView on main thread(which hopefully wont take long). Here when scroll somewhere I will need to calculate and create new UIView with objects and position it next to existing and eventualy to remove first UIView with all objects and layers when user continues to scroll in some direction.
Combine all layers in image with CoreGraphics and present them as objects with already decided layers. In this way I can remove specific object(image) from scroll view. When user scrolls I just create new objects and add them to view as full objects, and can remove objects when user scrolls enough instead of removing whole view. The problem here is adding multiple objects to UIScrollView on main thread, however when they are combined they won't be more than 15-20 objects.
My biggest concerns are performance and threading. As I said I cannot block main thread(or let's say cannot do this for a time that user will notice) and cannot combine images at my graphics department as they have tons of variatons which are decided at runtime. That's why I'm thinking of a way to prepare data on background thread and just really fast add it on main thread instead of preparing and adding it on main thread(which will block UI).
Every help will be greatly appriciated!
Regards,
hris.to
Look at using CATiledLayer for a UIView backing. It is was designed for this.
I have a map that has one UIView in a UIScrollView and the UIView is sized to the full size of the entire map. The CATiledLayer handles when to draw each tile of the view.
Ok, so I'm writing here just to let you know how I fix my issue.
Main problem was that I was moving a background picture while scrolling(so I don't load an enormous file) and while doing that I was fetching information from server and try to draw on the same tiles which makes system crash with well known crash:
CALayer was muted while enumerated
I was depending on performSelector method along with #synchronized but it turns out that this is not effective and sometimes two threads(main UI thread and background thread) were trying to change same tiles on screen. So basically what I did is to change background fetching and drawing from:
[self performSelectorOnBackgroundThread]
to using concrete background thread, to which I store reference:
#property(nonatomic, strong) NSThread* backgroundThread;
And now each time I need to load new tiles or I need to move background, I'm cancelling this thread(and make sure it's cancelled) before start any other operation. Also there was a little problem when switching between view with this thread and other views, as my thread hangs, and I needed to set a timeout:
[_backgroundThread cancel];
int currentAttempts = 0;
while( [_backgroundThread isExecuting] )
{
if( currentAttempts == MAX_ATTEMPTS_TO_CANCEL_THREAD )
{
//make sure we dont hang and force background
_backgroundThread = nil;
return;
}
[_backgroundThread cancel];
currentAttempts++;
}
In my 'scrollViewDidScroll' however, I didn't use the recursion as this results in slight UI blocks while scrolling on older devices(such as iPhone 4) which is unacceptable. So there I basically just cancel the thread and hope to get cancelled quick enough(which with dozens of tests appears to be working):
- (void)scrollViewDidScroll:(UIScrollView*)scrollView
{
[_backgroundThread cancel];
//move background around
[self moveBackground];
}
Downside of this approach is that you need lots of check in your background thread as calling 'cancel' to it won't actually cancel anything. As per apple docs it'll only change isCancelled state of your thread and you are responsible to make this thread quit in basically the same way as it'll quit normally(so the system has a chance to cleanup after your thread):
if( [_backgroundThread isCancelled] )
{
return;
}
Regards,
hris.to

Having UIView drawRect occur in a background thread

I would like to have a UIView subclass that implements a method similar to setNeedsDisplay, except that redrawing (i.e., that would usually be called via drawRect:) will occur in a background thread sometime soonish, rather than at the end of the current update cycle.
It might be called setNeedsAsynchronousDisplay. Or the existing setNeedsDisplay could get hijacked and not cause redraw at the end of the cycle, or whatever, as long as it lets the redraw not happen on the main thread blocking screen updating an interaction until its completed.
Until the redraw occurs, the view can continue to use its current drawn representation.
Is something along these lines reasonably doable?
Thanks!
Yes it is possible. You will probably need to generate the content view as an image in the background and push the images into a nsdictionary or array.
So while your background is generating the images you can just show the image in drawrect function by rendering the image, providing the image has been generated.
A WWDC video that shows how to do it: WWDC 2012 session 211 - Building Concurrent User Interfaces on IOS. Here is the video description:
For a great user experience, it's essential to keep your application responsive while it renders complex UI elements and processes data. Learn how to use concurrency at the UIKit layer to perform drawing and other common operations without blocking user interaction.
No. View Drawing must occur in the foreground. Apple makes that very clear in their docs.
EDIT: You're right that you CAN do Core Graphics drawing in the background as long as it's not in a UIView object's drawing methods. You'd have to do the drawing in the background, then send a message to the main thread to update your view object once drawing is complete.
I would suggest not trying to override setNeedsDisplay. Instead, add your new setNeedsAsynchronousDisplay method. In that method, queue rendering code to an async queue using GCD calls. Once the rendering is complete, have the rendering code send a setNeedsDisplay message to self on the main thread.
Then in your subclass's drawRect method, check for pre rendered images and draw those into the view's context instead of the normal code.
A downside of this is that merely by implementing drawRect, you may slow down rendering because the system calls that instead of doing other, more efficient things to render your view's content.

iOS slow to release images while scrolling (no tableview)

Here is the problem :
I am writing an app which displays some pictures, with a treemap layout (for an example, see https://raw.github.com/beckchr/ithaka-treemap/master/Core-API.png)
This layout is displayed in a UIScrollView. Since many pictures can be added to that scrollview, I want to release the ones which are not on currently on screen. I am not using ARC.
At my point, I know which pictures I should release, and how to do it while scrolling (calling some "unload" method). There is no useless call of that method. The problem is that, when pictures are released, the scrolling stops for a little moment (a few ms, but this is enough to be bad looking, making the scroll kind of "jumping" and slow, not smooth at all).
What I've tried (put in the body of my "unload" method) :
imageview.image = nil
performSelectorInBackground:#selector(effectiveUnload) withObject:nil
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0,^(void){
dispatch_sync(dispatch_get_main_queue(), ^(void){
imageview.image=nil}
}
I think this problem is weird, since there is absolutly no slowing effect with memory allocation, but only with memory release.
Thanks for help, don't hesitate to ask for more information.
did you try removeFromSuperview to remove the imageview from scrollview
Don't add more and more UIImageViews - recycle them!
To save as much memory as possible you should follow the UITableView way of recycling views:
1. Once a view has left the visible area, add it to a "views pool" (and remove it from its superview. It's not an expansive operation!)
2. When a new view becomes visible, first check if there's a view in the pool. If not, then create a new view.
I know my answer doesn't answer your question directly, but that's the way to go. Otherwise you'll run out of memory eventually.

View transitions slowed down on adding OpenGL view

Facing a really, really weird problem with an OpenGL View we are using in our app to perform some custom animations. As soon as the Open GL View is added into the project, all native View animations slow down. And by slow down I don't mean a drop in frame rate. The animations are stutter-free, except much much MUCH slower than normal (like someone enabled "Toggle Slow Animations" in the Simulator).
This is affecting only view transitions animations, for example:
a. transitionFromView
b. presentViewController (iOS6, or presentModalViewController on earlier)
While regular UIView Animations, CABasicAnimation etc proceed at the regular pace.
I haven't seen anything like this, and the results honestly have to be seen to be believed. :) But any idea what the problem could be (I'm not sure which piece of the code would help you debug, and I'm unfortunately not in a position to share screenshots or video)
It seems like the animation gets stuck while loading the OpenGL View, debug the
Lifecycle methods like loadView, viewWillLoad. The loadview, etc. happens within the
transition animation, maybe you can solve the slow animation by sending most of the loading
code in to a custom method which you call in viewdidload or viewdidappear.
It does not interrupt any other animation because thats a totally new action in the queue.
Hope this helps!
Found the solution accidentally several days later.
The problem turned out to be much sillier and unrelated. It so happens that if you have a UIView beginAnimation block that is not closed properly, future animations get all wonky. This faultily coded animation happened to be triggered at more or less the same time as the OpenGL view was being initialized, which led to my erroneous belief that the OpenGL View was at the root of this.
Thanks for the help!

UIimageView animation is using too much memory

I have two uiimageview animations. One on each of two view controllers in a navigation controller.
They have about 10-15 frames each. This is the smallest I can possibly make them.
They seem to be using a hell of a lot of memory though. Especially on startAnimating. Is there any way around this?
On my iPad this is causing a memory warning an a leak. I've tried looking into it, and as per an earlier question on here I've been using a lot of memory tools and such and narrowed the issue down to the startAnimating function.
I have read that this is because on startAnimating the imageView puts all the images into memory at this point.
However removing from superview and releasing dosen't seem to have a marked effect on the amount of memory reclaimed.
Is there any way around this? Bar creating a custom OpenGL style animation?
Thanks
Even i use to face same Problem.. I came up with solution by using custom navigation controller. Now i don't see any memory warnings or memory leaks.
Try to implement your own custom navigationController.

Resources