频道栏目
首页 > 资讯 > 其他综合 > 正文

使用category 为 AppDelegate 的代码分层

16-03-15        来源:[db:作者]  
收藏   我要投稿

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

 </uiapplicationdelegate></uikit>

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) 

-(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回调组件。

相关TAG标签
上一篇:Spring 实践之Java与设计模式 -拾遗
下一篇:通过一个大型项目来学习分布式算法(3)
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站