使用category 为 AppDelegate 的代码分层

来源:互联网 发布:数据库怎么导入 编辑:程序博客网 时间:2024/06/01 10:23

Category是一种为现有的类添加新方法的方式。


利用Objective-C的动态运行时分配机制,Category提供了一种比继承(inheritance)更为简洁的方法来对class进行扩展,

无需创建对象类的子类就能为现有的类添加新方法,可以为任何已经存在的class添加方法。


AppDelegate 是iOS app启动的入口,经常需要添加各类的第三方应用,比如:定位服务、统计服务、消息推送服务、支付服务等。

各类服务的代码如果完全放在一个文件中,给阅读和修改带来极大的不便。


利用category的特点,可以将不同的服务分别保存在不同的category(类)文件中,让代码更加简洁,结构层次更加分明,阅读和修改容易。


上代码!


一、环境





二、原始文件

1、AppDelegate.h

 #import <UIKit/UIKit.h>@interface AppDelegate : UIResponder <UIApplicationDelegate>@property (strong, nonatomic) UIWindow *window;@end 

2、AppDelegate.m


 #import "AppDelegate.h"@interface AppDelegate ()@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {      return YES;}- (void)applicationWillResignActive:(UIApplication *)application {    }- (void)applicationDidEnterBackground:(UIApplication *)application {    }- (void)applicationWillEnterForeground:(UIApplication *)application {   }- (void)applicationDidBecomeActive:(UIApplication *)application {   }- (void)applicationWillTerminate:(UIApplication *)application {    }@end  

三、创建AppDelegate的category

1、选中 AppDelegate.h

2、同时按住 command + shift + s ,将AppDelegate.h 另存为

3、名称 AppDelegate+WeixinPayService.h

4、同样操作,修改AppDelegate.m

5、将名称改为 AppDelegate+WeixinPayService.m

6、打开  AppDelegate+WeixinPayService.h 文件,修改

 #import "AppDelegate.h"#import "WXApi.h"@interface AppDelegate (WeixinPayService) <WXApiDelegate>-(void)initWeixnPayService:(UIApplication *)application WithOption:(NSDictionary *)launchOptions;@end 

7、打开 AppDelegate+WeixinPayService.m,修改

 #import "AppDelegate+WeixinPayService.h"@implementation AppDelegate (WeixinPayService)-(void)initWeixnPayService:(UIApplication *)application WithOption:(NSDictionary *)launchOptions{           [WXApi registerApp:@“xxxxxxxxxxxxxxxxxxxxxxxxx”];    }@end 

8、导入 weixinPayService到 AppDelegate.m中


 #import "AppDelegate+WeixinPayService.h" 



9、修改 AppDelegate.m 的代码

 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {      [self initWeixnPayService:application WithOption:launchOptions];        return YES;} 

10、在需要回调的其他方法中,以同样的方式回调WeixinPayService中自定义的方法。

上面代码中没有定义更多WeixinPayService的代码,需要自己根据需要自行添加。



以上这种方式,适合使用的服务比较少的应用,思路是利用Category从原有的类中抽取了代码另存,这样从AppDelegate中可以容易的跟踪代码。


如果添加的服务很多,那么尽管使用了command+shift+s,还是需要添加和修改比较多的代码。

多个服务之间,代码完全独立,没有任何的复用。多个服务使用上述方法,会使代码量增加的较多。


可以将上述代码进行重构,把多个服务的方法进行统一命名,然后做成服务组件进行自动调用。

组件中的服务就是应用需要的服务,每个服务只需要按照统一命名的方法进行开发并注册到组件中,那么服务对AppDelegate的回调自动完成。


基于服务的AppDelegate回调组件: http://blog.csdn.net/teamlet/article/details/50864893



0 0