简体   繁体   中英

Problem with my app delegate

I am trying to make an app that contains a class that is created in the app delegate. I initialize it with:

    Mobile *tmp = [[Mobile alloc] init];
    mobile = tmp;
    [tmp release];

and then I try to use it in other classes in my app with this:

    projectAppDelegate *delegate = (projectAppDelegate *)[[UIApplication sharedApplication] delegate];
    mobile = delegate.mobile;

but when I do something like:

[mobile enter:x :y];

it crashes...

Is there something I did wrong, or is there any solution for making a class that all the other classes in the app can use?

Thank you.

In your first code snippet you are effectively creating and immediately destroying the object. If the object is supposed to persist after that method is done executing you should just use

mobile = [[Mobile alloc] init];

If you want to use instances of your object you have to store them as properties of app delegate.

//appdelegate.h
//
//...
//
@interface AppDelegate : NSObject <UIApplicationDelegate> {
  Mobile *tmp;
}
//...

//appdelegate.m
//
//...
//
- (BOOL)application:(UIApplication *)application 
  didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  mobile = [[Mobile alloc]init];      
}
//...
-  (void)dealloc {
  [mobile release];
  [super dealloc];
//...
}

Than you have to get a pointer to your application delegate shared instance and call your mobile property.

//... Somewhere
AppDelegate* ref = (AppDelegate*) [[UIApplication sharedApplication] delegate];
NSLog(@"%@", [ref mobile]);
//...

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