Search code examples
iosparsingviewcontrollerviewdidload

Run a piece of code when viewController first appears


I'm using parse to store and retrieve data from and to my iOS app. My code is as follows.

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

    if (!error) {

        for (PFObject *item in objects) {

            self.postPlace.text =  [item objectForKey:@"place"];
        }
    }

    else {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];

However, on first view, I want the following code to be:

self.postPlace.text =  nil;

And then the rest of the time:

self.postPlace.text =  [item objectForKey:@"place"];

How can I implement this? I've looked into viewDidLoad and viewDidAppear, but I'm a little stuck.


Solution

  • As I have been in protracted discussion with the authors of the other two (at the time of writing) answers about their suggested use of a static local variable, I will provide my own answer, with what I think is a much better solution.

    The use of a static local variable to track if something has been done, or not, will limit the number of instances of the class to one, given there can be only one instance of a static local variable per-process. This might not be an issue for a View Controller, where only one instance might be required, however there are often cases where more than one instance of a view controller will be used and using a static local variable will cause a difficult-to-find bug later in development, especially as it's so inconspicuous.

    My suggestion would be to track your behaviour using an instance variable, allowing multiple instances of the class and making it obvious you are doing so, as it appears in the class @interface shouting out its purpose (if named correctly).

    Therefore:

    @interface MyViewController : UIViewController
    {
        BOOL _haveSetPostPlaceNil;
    }
    

    and in the code (there is no need to initialise it to NO unless you really feel the need), use:

    for (PFObject *item in objects) {
        if (!_haveSetPostPlaceNil) {
            self.postPlace.text = nil;
            _haveSetPostPlaceNil = YES;
        } else {
            self.postPlace.text = [item objectForKey:@"place"];
        }
    }