简体   繁体   中英

Bad access in using “setNeedsDisplay” method in background thread

There is a object dragging and video recording in my app. I am using a ScreenCapture view in my app. I am taking screenshots of main screen and making a video.

When I am using the following code in drawRect() method of my ScreenCapture view, the dragging becomes slow for iOS 6 and works fine for iOS 5:

[self performSelector:@selector(setNeedsDisplay) withObject:nil
      afterDelay:delayRemaining > 0.0 ? delayRemaining : 0.01];

And when i replace that line of code with following code, the dragging works fine but gives a bad access:

[self performSelectorInBackground:@selector(setNeedsDisplay) withObject:nil];

What is the reason for this?

You should only call UI methods in the main thread, so you cannot do that.

If your view is slow then you need to arrange to do expensive things in the background thread which will make drawing quicker in the main thread.

The actual method you are calling doesn't do anything much anyway; it simply marks the view for redraw. The work still needs to occur in the drawRect method.

Because of that drawRect method work only on mainThread. Apple document says that UIKit work only mainthread. so you need to setNeedsLayout in mainthread

UIKit control which are updating should NOT be called on main thread . as UIKit class is not thread safe.

I have used ScreenCaptureView class. In this case u can call another method in background and use drawRect code in that method as below,

[self performSelectorInBackground:@selector(callCodeInsideDrawRect) withObject:nil];



-(void)callCodeInsideDrawRect
{
 //any code which is required to be called in background (drawRectCode)
 //in ur case draw rect block

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM