Reputation: 1526
I have a Modal View Controller, and a Navigation View Controller embedded in a normal View Controller. Now, when someone clicks a UIBarButtonItem on my Navigation Bar, they go to the modal view controller. I have a custom UIAlertView which is a loading bar for retrieving the data for my app. I put this in the ViewWillAppear method. The problem is that if someone goes into the modal view controller and goes back to the navigation controller, the UIAlertView pops up again. Is there any way that I can make a method happen ONLY on launch? Any help would be appreciated. Thanks!
Here's some more info: I originally had it in ViewDidLoad (instead of ViewDidAppear), and the same thing kept appearing. I have a feeling that I might be doing something wrong with the implementing the modal view controller. I have my own custom navigation bar, so I'm hiding the normal navigation bar and I'm programmatically calling performSeguewithIdentifier.
Upvotes: 0
Views: 421
Reputation: 979
I got into similiar problems quite often so I added a function wrapper to my heavily used wrapper arround Async called Alinex-Async.
With this I can define make any function easily into one which may be called often but will only run once and for all further calls return the same result. It also responds correctly if it is called multiple times while running for the first time.
In CoffeeScript pseudo code it will be used like:
async = require 'alinex-async'
fn = async.once (cb) ->
result = do something
cb null, result
Alternative implementations which error on second call or return multiple times but only once at the same time are also available.
Upvotes: 1
Reputation: 613
You can try 'dispatch_once' if you are using GCD.
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
<#code to be executed once#>
});
Upvotes: 0
Reputation: 554
ViewDidLoad will fire every time your view loads, which can be more than once per session (i.e. a memory leak that released views). What I would do is create a boolean instance variable and in your init method set it to true. Then check to see that this boolean var is true before showing your alert view (either from viewWillAppear or viewDidLoad).
For example:
@interface YourViewController : UIViewController {
BOOL showAlert;
}
@end
@implementation YourViewController
- (id) init {
// initiate everything else and add this line
showAlert = true;
return self;
}
- (void) viewDidLoad {
if(showAlert) {
//UIAlertView... blah blah blah, show your view
showAlert = false;
}
}
@end
This ensures that your alert will only be shown once per session. Unless for some reason your ViewController should be released. In which case, you should store this BOOL in the AppDelegate.h class.
Upvotes: 1
Reputation: 6954
ViewDidLoad
Use this method instead of viewWillAppear
.
ViewDidLoad
is called once when it is loaded while viewWillAppear
is called everytime you enter that view.
Upvotes: 5