【问题标题】:AppDelegate class not found找不到 AppDelegate 类
【发布时间】:2012-02-06 15:55:50
【问题描述】:

我在很多类中导入了 AppDelegate.h:

#import "AppDelegate.h"

@interface LoginViewController : UIViewController<UITextFieldDelegate>
{

}

@property (nonatomic, retain) AppDelegate *app;

但不知何故,它在我的 loginviewcontroller.h 中停止工作。它说:

 unknown type name 'AppDelegate' [1]
 property with 'retain (or strong)' attribute must be of object type [3]

我一开始就开设了这门课,它总是按预期工作。当这个错误开始时,我没有对类或AppDelegate 进行任何更改。

我可以毫无问题地将它导入其他类。我也尝试重新创建课程,但没有帮助。

有人知道如何解决这个奇怪的错误吗?

【问题讨论】:

  • 您的 .h 文件中是否可能存在循环依赖关系? (最简单的方法:#import "LoginViewController.h" 在您的 AppDelegate.h 中)。如果是这样,您可以在此处使用 @class AppDelegate 而不是导入并在 LoginViewController.m 中进行导入
  • 我认为确实是这样,我在 appdelegate.h 中导入了 loginviewcontroller.h,在 loginviewcontroller.h 中导入了 appdelegate.h。将 loginviewcontroller 的导入移动到 .m 中,在我的 loginviewcontroller 中,我只在需要的方法中调用 AppDelegate* appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate]。

标签: ios delegates import uiapplicationdelegate


【解决方案1】:

使用这行代码不是个好主意

@property (nonatomic, retain) AppDelegate *app;

在你需要的每一堂课中。在您需要的地方访问委托应用程序的简单方法是执行以下操作:

AppDelegate* appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];

显然你需要这样做:

#import "AppDelegate.h"

在你使用它的类中。

如果您想要更简洁的方式来执行此操作,可以在 AppDelegate.h 中创建一个类方法,如下所示:

+(AppDelegate*)sharedAppdelegate;

在 AppDelegate.m 中定义如下:

+(AppDelegate*)sharedAppdelegate
{
    return (AppDelegate*)[[UIApplication sharedApplication] delegate];
}

然后,您可以在需要的地方调用(在导入 AppDelegate.h 之后):

AppDelegate* sharedApp = [AppDelegate sharedAppdelegate];

希望对你有帮助。

P.S.为什么需要访问代理?

【讨论】:

  • 就像你说的那样,它在 .m 中确实有效。需要在委托中,以便我可以从 tabbarcontroller 更改(有 2 个并且都存储在主窗口中)。
【解决方案2】:

在 .h 文件中声明前向引用

@class AppDelegate

@interface LoginViewController : UIViewController<UITextFieldDelegate>
{

}

// 将其保留为分配而不是保留,以保持变量的 retainCount 水平

@property (nonatomic, assign) AppDelegate *app;

在 .m 文件中,通过导入 AppDelegate.h 并分配变量来获取指向 Appdelegate 的指针

#import "AppDelegate.h"

- (void)viewDidLoad
{
   self.app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
   //use the variable.
}

【讨论】:

  • 在我的 viewdidload 中有相同的代码行。尝试使用分配而不是保留,但没有帮助。
  • 导入 AppDelegate.h 文件后,仅此行即可为您工作。 AppDelegate* appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];//现在使用appDel
  • 实际上我没有看到 self.app = (AppDelegate*)[[UIApplication sharedApplication] delegate]; 的任何理由不为你工作。实际上你正在运行 AppDelegate.h 文件。 AppDelegate* appDel = (AppDelegate*)[[UIApplication sharedApplication] delegate];//现在使用 appDel,每次你得到 AppDelegate 的 sharedInstance 并且如果你丢失了 (assign) 类型的变量,这意味着有一些问题您的代码(与内存相关)正在破坏您的控制器数据。您需要针对此问题进行相同的调试,否则稍后会给您带来问题。
  • 行 self.app = (AppDelegate*)[[UIApplication sharedApplication] delegate];起作用了,是 .h 文件中的那一行出现了问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多