[iOS]APP代碼實踐:建立一個輔助的APP類,減少對AppDelegate的修改
最開始接觸iOS開發的時候,如果需要一些全域變數或者全域函數的時候,總是直接在AppDelegate
中添加,因為AppDelegate
可以直接擷取
[UIApplication sharedApplication].delegate
但是時間長了還是覺得這樣不太好,AppDelegate
本身有其自己的作用(對於App本身的一些事件進行處理,如啟動,切換,推送),這樣做感覺怪怪的,所以還是自己弄一個專門處理我們所需的全域變亮或者全域函數的對象會更好一些
//APPHelper.h@interface APPHelper+ (APPHelper*)call;- (void) configureWindow:(UIWindow*)window;@property (nonatomic, readonly) AppDelegate *delegate;@property (strong, readonly) UIWindow *window;@end//APPHelper.m@interface APPHelper ()@end@implementation APPHelper- (id)init{ self = [super init]; if (self) { _delegate = (GGAppDelegate*)[UIApplication sharedApplication].delegate; } return self;}+ (APPHelper *)call{ static dispatch_once_t onceQueue; static APPHelper *appInstance; dispatch_once(&onceQueue, ^{ appInstance = [[APPHelper alloc] init]; }); return appInstance;}- (UIWindow *)window{ return self.delegate.window;}- (void)configureWindow:(UIWindow*)window{ UINavigationController *nav = [[UINavigationController alloc] init]; ... ... ... window.rootViewController = nav; }@end
然後 在先行編譯頭*.pch
中加入
#import "AppHelper.h"#define APP ([APPHelper call])
就可以直接在代碼的任意一個地方直接使用此類了,如
//設定APP為圓角APP.window.layer.cornerRadius = 5.0f;APP.window.layer.masksToBounds = YES;