ohh*_*hho 29 iphone singleton delegates objective-c
我将全局变量存储在AppDelegate中并通过以下方式访问它们:
AppDelegate *d = [[UIApplication sharedApplication] delegate];
d.someString = ...
Run Code Online (Sandbox Code Playgroud)
什么是保存一些打字的推荐方法,所以我不需要AppDelegate *d = [[UIApplication sharedApplication] delegate];一次又一次?谢谢!
Nev*_*vin 41
正如Shaggy Frog所说,在YourAppDelegate.h文件中定义一个宏,如下所示:
#define AppDelegate (YourAppDelegate *)[[UIApplication sharedApplication] delegate]
Run Code Online (Sandbox Code Playgroud)
然后,您可以在代码中获取应用程序委托,如下所示:
[AppDelegate ......];
Run Code Online (Sandbox Code Playgroud)
Jas*_*oco 11
由于您的应用程序委托永远不会真正更改,因此您可以创建在应用程序委托代码中定义的外部程序,非常类似于NSAppMac OS X Cocoa应用程序的外部程序.
因此,在AppDelegate标头中定义外部(或者包含在任何地方的其他内容):
extern AppDelegate* appDelegate;
Run Code Online (Sandbox Code Playgroud)
然后创建它并在实现文件中设置它:
AppDelegate* appDelegate = nil;
// later -- i can't recall the actual method name, but you get the idea
- (BOOL)applicationDidFinishLaunchingWithOptions:(NSDictionary*)options
{
appDelegate = self;
// do other stuff
return YES;
}
Run Code Online (Sandbox Code Playgroud)
然后其他类可以访问它:
#import "AppDelegate.h"
// later
- (void)doSomethingGreat
{
NSDictionary* mySettings = [appDelegate settings];
if( [[mySettings objectForKey:@"stupidOptionSet"] boolValue] ) {
// do something stupid
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19294 次 |
| 最近记录: |