問題:每個新的iOS都添加了許多新的有用類。例如,UIRefreshControl。我想在iOS5 build中添加對這個類的支持。Objective-c爲舊設備添加對新類的支持
不冷靜解決:在必須使用UIRefreshControl所有類,我可以檢查當前的iOS版本,並使用內聯替代的類,例如:
pseudocode
...
- (void)viewDidLoad
{
...
if([[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
self.refreshControl = [[MyCustonRefreshControl_for_iOS5 alloc] init];
}
else
{
self.refreshControl = [[UIRefreshControl alloc] init];
}
...
}
該解決方案豈不等於冷靜,因爲我必須在所有需要使用最新iOS功能的課程中添加相同的代碼。
可能的陰涼解決: 1)獲取或創建自己的100%兼容類,例如用於UIRefreshControl可以使用CKRefreshControl(https://github.com/instructure/CKRefreshControl); 2)使用Objective-C運行時在App啓動時將替換類定義爲主類。
pseudocode
...
// ios 5 compatibility
#include <objc/runtime.h>
#import "CKRefreshControl.h"
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
// pre-ios 6 compatibility
if([[UIDevice currentDevice].systemVersion floatValue] < 6.0)
{
// register refresh control
Class clazz = objc_allocateClassPair([CKRefreshControl class], "UIRefreshControl", 0);
objc_registerClassPair(clazz);
}
...
}
我認爲這種方式真的很酷,但是這段代碼不起作用。
它不是Objective-c或可可風格,這種方式在java中經常使用。 – abuharsky
這是一個可以在Objective-C中使用的設計模式。面向對象的應用程序設計原則和模式也堅持Objective-C編程。 –