【问题标题】:iPhone, how do usa an App Delegate variable so it can be used like global variables?iPhone,如何使用 App Delegate 变量使其可以像全局变量一样使用?
【发布时间】:2010-09-30 17:42:11
【问题描述】:

这是我正在使用的代码,稍后查看我的错误

@interface MyAppDelegate : NSObject  {
  NSString *userName;
}
@property (nonatomic, retain) NSString *userName;
...
@end

在 App Delegate 的 .M 文件中,您可以编写:

@implementation MyAppDelegate
@synthesize userName;
...
@end

然后,每当你想获取或写入用户名时,你会写:

MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
someClass.someString = appDelegate.userName;  //..to fetch
appDelegate.userName = ..some NSString..;     //..to write

警告:类型“id”不符合“MyAppDelegate”协议

我的代码中缺少什么?

【问题讨论】:

    标签: iphone xcode iphone-sdk-3.0


    【解决方案1】:

    您应该向 MyAppDelegate 添加演员表

    MyAppDelegate *appDelegate = (MyAppDelegate*)[[UIApplication sharedApplication] delegate];

    【讨论】:

    • 这是答案——当您从 UIApplication 中提取引用时,将其转换为您的 App Delegate 类型。也就是说,如果您有许多此类数据字段,则应考虑将它们存放在数据管理器单例中。将所有数据保留为应用程序委托的属性并不是一个好方法。
    • Dan,我同意,对于此类托管,AppDelegate 并不是最佳实践。
    • 我在使用 NSNumber 和 NSString 时出现错误,请参阅下面的代码。
    • 你应该做 intValue 而不是 integerValue
    • 这可能应该作为一个单独的问题提出,因为我无法在评论中输入格式正确的答案。基本上,数组只存储对象,而不是原始类型,所以当它需要一个整数时,你将一个对象传递给 numberWithInt:。
    【解决方案2】:

    是的,您可以通过将其设为全局来访问任何变量值。

    例如:

    AppDelegate.h

    {
        NSString *username;
    }
    
    @property (strong,nonatomic) NSString *username;
    

    AppDelegate.m(在@implementation 块中)

    @synthesize username;
    

    AnyViewController.h

    #import AppDelegate.h
    

    AnyViewController.m

    //Whatever place you want to access this field value you can use it like.
    
    AppDelegate *appdel=(AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    NSString *unm=appdel.username;
    
    //You can get the username value here.
    NSLog(@"%@",unm);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多