pushViewController Taking too much to show the view - objective-c

I have a really light ViewController, it does nothing in viewDidLoad. I'm pushing this view on top of a navigationController. The method who does this action is called from inside a block. After the call to showView I added an NSLog, and that log prints in the console really fast, but the view takes a lot to load... I really don't understand what maybe happening... any idea???
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error) {
[self showView];
NSLog(#"EXECUTED");
});
- (void) showView{
TestViewController *test = [[TestViewController alloc]init];
[self.navigationController pushViewController:test animated:NO];
}

From the docs for ABAddressBookRequestAccessWithCompletion:
The completion handler is called on an arbitrary queue. If your app uses an address book throughout the app, you are responsible for ensuring that all usage of that address book is dispatched to a single queue to ensure correct thread-safe operation.
You should make sure your UI code is called on the main thread.
ABAddressBookRequestAccessWithCompletion(addressBookRef, ^(bool granted, CFErrorRef error {
dispatch_async(dispatch_get_main_queue(), ^{
[self showView];
NSLog(#"EXECUTED");
});
});

This might not be the only problem, but according to the docs, the completion handler passed to ABAddressBookRequestAccessWithCompletion is called on an arbitrary queue. -showView should only be called on the main queue since it is dealing with UIViewController objects.
The other thing to ask is what else is happening on the main queue? Are there other long-running tasks that could be blocking UI updates?

Related

Why is WKInterfaceLabel text not refreshing

The WatchApp receives data from the iPhone.
I refresh the label text with the data received, nothing happens, the UI is not refreshing.
Other threads suggested pushing it to the main thread and that seems to do nothing either.
Any thoughts most welcome.
-(void)session:(nonnull WCSession *)session didReceiveApplicationContext:(nonnull NSDictionary *)applicationContext
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.lblTitleBorH setText:#"test"];
});
}
Are you using
[*your session* updateApplicationContext:*your dictionary* error:nil];
correctly?
try putting a NSLog inside your above didReceiveApplicationContext code and see if it is printing anything out.
In my case, when I tried to refresh the UI, I found that the outlet references were nil. The problem was caused by two interfaces on the storyboard, belonging to the same WKInterfaceController class.
When I assigned the second screen interface to another WKInterfaceController class it worked fine.
remember to call the UI objects from the main thread by using
dispatch_async(dispatch_get_main_queue(), ^{
...
});
or by using methods like performSelectorOnMainThread: withObject: waitUntilDone:

Is is more efficient to call dispatch_async once or multiple times

I am trying to understand the run loop. Which is the best way to code this?
for (UIView *view in self.viewSet) {
dispatch_async(dispatch_get_main_queue(), ^{
[view removeFromSuperview];
});
}
or
dispatch_async(dispatch_get_main_queue(), ^{
for (UIView *view in self.viewSet) {
[view removeFromSuperview];
}
});
To answer the question specifically, it breaks down into the size of units of work. If you dispatch a really large chunk of work to the main thread, then that large chunk will block the main thread for the entire time it is processing. If you dispatch a bunch really small chunks of work to the main thread, then the main thread will interleave processing of the chunks of work with processing of other events which will make your app slightly less efficient, but overall more responsive.
However, in the context of the question asked, neither dispatch_async() pattern is likely to be what you really want. You really shouldn't be removing a ton of views from any superview, whether it be all at once or interleaved on the main queue.
Instead, you should have a container view that contains the views that need to be swapped out-- potentially managed by a view controller-- and you should have one removeFromSuperview that removes that container. Once removed, then there really shouldn't be a need to manually remove any of the container views as you should have defined the retain/weak ownership rules such that you don't have cycles through view -> subview relationships.
Or, succinctly:
dispatch_async(.. main queue .., ^{
[_myContainerView removeFromSuperview];
});
In an ideal world, that removeFromSuperview would remove the last reference to _myContainerView and then it'd automatically tear down the hierarchy of subviews as the UIKit sees fit.
The first one
for (UIView *view in self.viewSet) {
dispatch_async(dispatch_get_main_queue(), ^{
[view removeFromSuperview];
});
}
queues up a bunch of [view removeFromSuperview] calls on the main thread. After the loop is over, they are executed one at a time. Each call is stuck waiting until the main queue clears, like a train waiting to pull into a station.
The second one
dispatch_async(dispatch_get_main_queue(), ^{
for (UIView *view in self.viewSet) {
[view removeFromSuperview];
}
});
queues just one thing onto the main thread, namely the whole loop. As soon as the main thread is free, a single piece of code runs, in which all the views are removed, kaboom.

addSubview waits for rest of method

I would like show my view immediately when I call it. I don't know how to make the view show.
-(IBAction) showProgress: (id) sender {
progressViewController *progress = [[progressViewController alloc] initWithNibName:#"progressViewController" bundle:NULL];
[self.view addSubview:progress.view];
[self someFunctionWhichTakesAgesToBeDone];
}
It's called from current UIViewController. And the view appears after the long function. How can I show it before the long funcion? Thanks for answer.
Use GCD (Grand Central Dispatch) which is the simplest way (and recommended by Apple), the code will then be:
-(IBAction) showProgress: (id) sender {
progressViewController *progress = [[progressViewController alloc] initWithNibName:#"progressViewController" bundle:NULL];
[self.view addSubview:progress.view];
// Heavy work dispatched to a separate thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"dispatched");
// Do heavy or time consuming work
[self someFunctionWhichTakesAgesToBeDone];
// When finished call back on the main thread:
dispatch_async(dispatch_get_main_queue(), ^{
// Return data and update on the main thread
});
});
}
It´s two blocks. The first one does the heavy work on a separate thread and then a second block is called when the heavy work is finished so that changes and UI updates are done on the main thread, if needed.
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nsobject_Class/Reference/Reference.html
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait`
use
[self.view performSelectorOnMainThread:#selector(addSubview:) withObject:progress.view waitUntilDone:YES]
or put your Sleep() function (i hope it's anything else, Sleep() func is really bad, as its been told) into another function MySleepFunc and call
[self performSelector:#selector(MySleepFunc) withObject:nil afterDelay:0.003]
instead of Sleep(3).
Read about multi-threading. In short, there's single UI thread that does drawing, accepting user events and so on. If you pause it with sleep() or any other blocking method, nothing will be shown/redrawn and no events will be processed. You have to make your HTTP request from background thread.

Does calling dispatch_sync(dispatch_get_global_queue()) on main thread cause app to "hang"?

// Method called when a button is clicked
- (void)handleClickEvent {
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self backgroundProcessing];
});
// Some code to update the UI of the view
....
[self updateUI];
....
}
1) handleClickEvent is called on the main thread when a button on the view is pressed.
2) I used dispatch_sync() because the following code that updates the UI of the view cannot be done until a variable in the backgroundProcessing method is calculated.
3) I used dispatch_get_global_queue in order to get the backgroundProcessing off the main thread. (following the rule: generally put background processing off main thread and generally put code that affect the UI on the main thread).
My question is: Does the backgroundProcessing method "hang" the main thread until it is complete since I am using dispatch_sync?
EDIT:
Based on the answer below i have implemented this solution:
- (void)handleClickEvent {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self backgroundProcessing];
dispatch_async(dispatch_get_main_queue(), ^{
[self updateUI];
});
});
}
solution from this link: Completion Callbaks
Yes, dispatch_sync will block until the task is complete. Use dispatch_async and when the job is complete have it post a block back to the main queue to update the view.

NSOperationQueue and UITableView release is crashing my app

This is by far the weirdest problem I've been stuck with.
I have a UIViewController on a UINavigationController and I want to call a method at viewDidAppear using NSInvocationOperation so it can run on a back thread when the view becomes visible.
The problem is that if I pop the view controller BEFORE the operation (in this case the testMethod method) completes running, the app crashes.
Everything works fine if I pop the view controller AFTER the operation runs it's course.
When the app crashes, it stops at [super dealloc] with "EXC-BAD-ACCESS" and gives me the following error.
bool _WebTryThreadLock(bool), xxxxxxxxx: Tried to obtain the web lock
from a thread other than the main thread or the web thread. This may
be a result of calling to UIKit from a secondary thread. Crashing
now...
And this is my code (super simplified)..
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSInvocationOperation *theOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:#selector(testMethod) object:nil];
[operationQueue addOperation:theOperation];
[theOperation release];
}
- (void)testMethod
{
NSLog(#"do some stuff that takes a few seconds to complete");
}
- (void)dealloc
{
[_tableView release];
[super dealloc];
}
The testMethod has some code that takes a few seconds to complete. I only have a few clues and I really don't know how and where to start debugging this.
Clue #1: The funniest thing is that if I remove the [_tableView release]; from dealloc then the app doesn't crash. But of course this would cause a leak and I can't remove it.
Clue #2: I've tested this code on a separate "clean" UIViewController with a UITableView and to my surprise it didn't crash.
Clue #3: The app doesn't crash is the UITableView's datasource is set to nil in viewDidLoad.
Clue #4: The app doesn't seem crash if I use the same code in viewDidAppear somewhere else like an IBAction.
Clue #5: I've tried looking over stack data with NSZombie but it gives me tons of data and it leads me nowhere.
I have some very complicated code within my UITableViewDelegate and UITableViewDataSource and I really don't know where to start debugging this. I really hope I don't have to go through line by line or rewrite the entire thing because of this.
Any pointers on where I should be looking?
The problem is likely that your view controller's last reference is the operation queue holding onto it, which means you are technically calling (or having the system call) some UIKit methods in a background thread (a big no-no) when the operation cleans up.
To prevent this from happening, you need to send a keep-alive message to your controller on the main thread at the end of your operation, by adding something like this to the last line in your testMethod:
[self performSelectorOnMainThread:#selector(description) withObject:nil waitUntilDone:NO];
There is still a chance that this message may get processed before the operation queue releases your view controller, but that chance is pretty remote. If it's still happening, you could do something like this:
[self performSelectorOnMainThread:#selector(keepAlive:)
withObject:[NSNumber numberWithBool:YES]
waitUntilDone:NO];
- (void)keepAlive:(NSNumber *)fromBackground
{
if (fromBackground)
[self performSelector:#selector(keepAlive:) withObject:nil afterDelay:1];
}
By sending a message to your view controller on the main thread, it will keep the object alive (NSObject retains your view controller until the main thread handles the message). It will also keep the view controller alive if you perform a selector after a delay.
You're crashing because the controller is still trying to use your tableView reference and since you poped the viewController, everything will go away in the dealloc and the tableView is still populating itself.
You can try asking in your dealloc method if your operation is still running, so you can cancel it and the everything should be fine.
Once you add an operation to a queue, the operation is out of your
hands. The queue takes over and handles the scheduling of that task.
However, if you decide later that you do not want to execute the
operation after all—because the user pressed a cancel button in a
progress panel or quit the application, for example—you can cancel the
operation to prevent it from consuming CPU time needlessly. You do
this by calling the cancel method of the operation object itself or by
calling the cancelAllOperations method of the NSOperationQueue class.
Cancelling an operation does not immediately force it to stop what it
is doing. Although respecting the value returned by the isCancelled is
expected of all operations, your code must explicitly check the value
returned by this method and abort as needed. The default
implementation of NSOperation does include checks for cancellation.
For example, if you cancel an operation before its start method is
called, the start method exits without starting the task.