1

I've been banging my head against the wall for several days trying to understand how to perform an action as soon as the application starts.

Basically I want to download a plist from my website if the user turns on a switch that determines if he wants to download new contents at startup.

Point is that:

  • "A" class has the method to reload the contents;
  • "B" class has the switch that, if turned on, tells the delegate to perform the reload contents method as soon as the application starts

Now, I don't know how to tell the AppDelegate to run the method of class "A" if the switch of class "B" is turned on. Obviously I need to use NSUserDefaults, but i'm pretty lost after that.

Can anyone make things clearer? Or, is there a more comfortable workaround to do it?

Phillip
  • 4,276
  • 7
  • 42
  • 74

2 Answers2

2

yes you can do this using NSUserDefaults

in your class b.

-(void)swithChanged
 {
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //check if !null
   if(![[defaults objectForKey:@"shouldDownload"]isKindOfClass:[NSNull class]]){
         if([(NSNumber*)[defaults objectForKey:@"shouldDownload"]boolValue])
          {
             [defaults setObject:[NSNumber numberWithInt:0] forKey:@"shouldDownload"];
             [defaults synchronize];
          }else{
             [defaults setObject:[NSNumber numberWithInt:1] forKey:@"shouldDownload"];
             [defaults synchronize];

         }
     }else{
       //set your NSUserDefault here for the first time
    }

}

in your AppDelegate

- (void)applicationDidBecomeActive:(UIApplication *)application{
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //check if !null
   if(![[defaults objectForKey:@"shouldDownload"]isKindOfClass:[NSNull class]]){
         if([(NSNumber*)[defaults objectForKey:@"shouldDownload"]boolValue])
          { 
              //you can write the downloadData method in this appDelegate,
             //[self downloadData]

             //OR
             AClass *aClass = [AClass alloc]init];
             [aClass downloadData];
          }else{
            //do not download
         }
     }else{
       //the default behaviour of app, download or not?
    }

}
janusfidel
  • 8,036
  • 4
  • 30
  • 53
  • Thanks a lot for the answer! Just a question: in AppDelegate, when you've wrote [self downloadData], i should initialize my "A" class then perform the method, right!? – Phillip Sep 03 '12 at 12:42
1

Here's a post that could help you understand the flows during application start-up: http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging

Also, check this post: applicationWillEnterForeground vs. applicationDidBecomeActive, applicationWillResignActive vs. applicationDidEnterBackground

Community
  • 1
  • 1
Bijoy Thangaraj
  • 5,434
  • 4
  • 43
  • 70