先說明一下。以前寫代碼時,view和viewcontroller是結合很緊密的,尤爲是viewcontroller,這裏面寫了對view的控制和業務邏輯,還有數據的操做。一點都很差。設計模式
如今增長了一層service,用於業務邏輯和數據的操做。viewcontroller只用於view的控制和欄位的check。atom
#import <UIKit/UIKit.h> //#import "IServicebase.h" @interface UIViewController (DEcontroller) @property (nonatomic, retain) NSString *classname; @property (nonatomic,retain) id classobj; -(instancetype)initforvmobjname:(NSString *) vmname datamap:(NSDictionary *)dataDic; @end #import "UIViewController+DEcontroller.h" #import "IServicebase.h" #import <objc/runtime.h> @implementation UIViewController (DEcontroller) //@synthesize height; - (NSString *)classname { return objc_getAssociatedObject(self, @"classname"); } - (void)setClassname:(NSString *)classname { objc_setAssociatedObject(self, @"classname", classname, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } - (id )classobj { return objc_getAssociatedObject(self, @"classobj"); } - (void)setClassobj:(id )classobj { objc_setAssociatedObject(self, @"classobj", classobj, OBJC_ASSOCIATION_RETAIN_NONATOMIC); } -(instancetype)initforvmobjname:(NSString *) vmname datamap:(NSDictionary *)dataDic{ UIViewController *selfobj = [self init]; Class someClass = NSClassFromString(vmname); id obj = [[someClass alloc] init]; if (!obj) { return nil; }else{ selfobj.classobj = obj; selfobj.classname = vmname; if ( [obj respondsToSelector:@selector(initclassdata:)] ){ [obj initclassdata:dataDic]; } } return selfobj; } @end
上述代碼,我用到了分類。在分類中原本是不能使用屬性的,只能有方法。但經過spa
#import <objc/runtime.h> - (NSString *)classname { return objc_getAssociatedObject(self, @"classname"); } - (void)setClassname:(NSString *)classname { objc_setAssociatedObject(self, @"classname", classname, OBJC_ASSOCIATION_RETAIN_NONATOMIC); }
這種作法來實現。設計
我把UIviewcontroller進行了擴展。每一個viewcontroller都有一個依賴service。code
#import <UIKit/UIKit.h> @interface IServicebase:NSObject -(void) initclassdata:(NSDictionary *)dataDic; @end #import <Foundation/Foundation.h> #import "IServicebase.h" @implementation IServicebase -(void) initclassdata:(NSDictionary *)dataDic{ NSLog(@">>>>>>>>>>>>>>>abc<<<<<<<<<<<<<<<<"); } @end
上述就是service,依賴於viewcontroller。這樣的設計模式就把軟件分層,各層耦合度下降。ci
view----viewcontroller----service----model,大體四層結構。get
目前仍是初步實現,有高人看到歡迎指點。it