我的应用代表有问题

时间:2011-03-27 22:43:54

标签: iphone objective-c delegates

我正在尝试创建一个包含在app delegate中创建的类的应用程序。 我用它初始化它:

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

然后我尝试在我的应用程序的其他类中使用它:

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

但是当我这样做时:

[mobile enter:x :y];

它崩溃了......

我做错了什么,或者是否有任何解决方案可以创建应用程序中所有其他类都可以使用的类?

谢谢。

2 个答案:

答案 0 :(得分:0)

在您的第一个代码段中,您正在有效地创建并立即销毁该对象。如果在该方法执行完毕后该对象应该保持不变,那么您应该只使用

mobile = [[Mobile alloc] init];

答案 1 :(得分:0)

如果要使用对象的实例,则必须将它们存储为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];
//...
}

您必须获得指向应用程序的指针委托共享实例并调用您的mobile属性。

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