作者:朱克鋒
轉載請註明出處:http://blog.csdn.net/linux_zkf
Objective-C的運行時支持新增類型和方法,但是由於蘋果的限制,開發者無法在iOS上動態加載Objective-C原生代碼,所以只能尋求替代方案。
腳本語言就可以一定程度上解決這一問題,一般情況下可以使用html+js實現例如支付寶的插件的實現就是用的是html+js技術,也可以基於lua腳本實現,下面介紹wax+lua的實現方式
關於wax請參見下面的連接
Wax項目(http://github.com/probablycorey/wax)
當然多數熟悉iOS的開發人員不一定會贊同採用這種開發方式,所以我們在引入Wax的同時希望能夠和已有的iOS項目無縫的結合起來,不改變項目使用Objective-C開發的方式,在項目上線後通過Wax來改變程序運行時的行爲。這樣就可以避免漫長的AppStore上線審覈,隨時對線上程序進行調整,甚至是修復線上程序的問題或缺陷。
下面是IOS代碼,這裏是IOS列表的簡單的幾個接口的實現,其實只是寫了一下接口,並沒有實現具體的方法,只是爲了和lua腳本做個比較
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return20;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell =[[UITableViewCellalloc] initWithStyle:UITableViewCellStyleSubtitlereuseIdentifier:@"Cell"];
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
下面是基於wax的lua代碼,看上去和IOS原生方法有很多類似的地方,不過要注意lua特殊的語法格式,下面有風雲翻譯的lua教程可以參考學習
waxClass{"LIViewController",UITableViewController}
function viewDidLoad(self)
print("viewDidLoad")
end
function tableView_numberOfRowsInSection(self, tableView,section)
return 20;
end
function tableView_cellForRowAtIndexPath(self, tableView,indexPath)
local cell =self:ORIGtableView_cellForRowAtIndexPath(tableView, indexPath)
cell:textLabel():setText("".. indexPath:row())
cell:detailTextLabel():setText("TESTDATA LUA HUHUHU~~~")
cell:textLabel():setTextColor(UIColor:redColor())
print("cell num is :" .. indexPath:row())
--if (1 ==indexPath:row()) then
--print("OMG---------!!!!!!!")
--end
return cell
end
function tableView_didDeselectRowAtIndexPath(self,tableView, indexPath)
print("you selected row num is : "..indexPath:row())
end
基於wax的lua使用並不複雜,下面就是一種很簡單的實現方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
self.window = [[[UIWindowalloc] initWithFrame:[[UIScreenmainScreen] bounds]]autorelease];
// Override point for customization after applicationlaunch.
wax_start("init.lua",nil);
self.viewController = [[LIViewControlleralloc] init];
self.window.rootViewController =self.viewController;
[self.windowmakeKeyAndVisible];
returnYES;
}
Lua腳本的編寫方式和Objective-C有很多的相似支出,在方法和類名上都和iOS的原生框架保持了一致。iOS開發人員只需要略微瞭解一下Lua的語法,就可以編寫對應的Lua補丁。更多的細節可以參見Wax項目的介紹:https://github.com/probablycorey/wax/wiki/Overview。
需要注意的是Wax項目本身不支持方法覆蓋和從Objective-C反向調用Lua修改後的實例
lua語法參照
http://www.codingnow.com/2000/download/lua_manual.html
項目代碼地址
https://github.com/zhukefeng-ios/LuaIOS