The hero Town building

The main use here is a cloud dad’s hot repair technology. The code is written based on Lua. (Please note the source for reprint)

I didn’t learn Lua syntax when I first contacted Lua Hotfix. It took a lot of work to convert to OC native code. Search everywhere and you can’t find how to switch. I had a little bit of documentation. There’s nothing I can do but try.

< mainly to record luA code into OC code, convenient for everyone to learn reference >

Replace the original method

1 Locate the specific class file

interface{"XXXController"}

Note that interfaces do not need to end

2 Locate the method

Function (self) function is required to end. This means that after the method is finished, an end is added to indicate the end.

You have to pay attention to self here, you can’t leave it out, otherwise inside the method, you can’t get the class value that’s the property value. In other words, all self inside the method is empty. It can crash.

Methods with multiple arguments are concatenated with underscores, passing the arguments in parentheses. Here’s an example of a dataSource method that must be implemented for tableView in the OC code, which looks like this

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

The code for converting to Lua is as follows

function tableView_ cellForRowAtIndexPath(self, tableView, indexPath)

3 Object creation

When creating an object, you don’t need to alloc, just init it with colon parentheses, for example:

local view = UIView:init()

Get the OC attribute usage method without point syntax, for example:

view:backgroundColor()

Set the OC property using the set method, not directly =

self:label():setText('XXX')

4 Simple combat

Some of the methods that need to be replaced do not need to be modified, for example

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"Before modification";
    [self loadData];
}
Copy the code

I just want to change at sign before to at sign after. And everything else stays the same. The conversion to Lua is as follows

functionViewDidLoad (self) self.super:viewDidLoad(self) Operate the self: the navigationItem () :setTitle('After modification');
self:loadData(self)
end
Copy the code

And then there’s another scenario that’s a little bit more nerve-racking

- (void)viewDidLoad {
    [super viewDidLoad];
    if ([XXX isEqualToString:@Judging "1"]) {
         self.navigationItem.title = @"Before modification";
    }else{// a lot of innocent code without mistakes. No need to modify}}Copy the code

As I understood it, the smallest unit Lua can locate is a method. Could not locate a line of code. If there is a lot of code in this method, it is very difficult to convert to Lua next. We don’t have to go to all this trouble. We can write it this way

function viewDidLoad(self)
self.super:viewDidLoad(self) 
if XXX == Judge '1'
	then 	
        self:navigationItem():setTitle('After modification');
elseSelf :ORIGviewDidLoad() -- don't pass self end endCopy the code

Create/add a UIViewController class

interface{"XXXController", UIViewController}
function init(self)
self.super:initWithNibName_bundle("MyControllerView.xib", nil)
return self
end

function viewDidLoad(self)
end
Copy the code

Add a new class and declare the protocol, for example

interface{"XXXClass", NSObject, protocols = {"UITableViewDelegate"."UITableViewDataSource}}"Copy the code

Some pits encountered in actual combat (updated continuously)

All strings returned in Lua are Lua strings. You cannot call NSString methods directly, otherwise you will report nil value errors

if  stringOne:isEqualToString('stringTwo') then
end
Copy the code

The correct way is as follows

if  stringOne == 'stringTwo' then
end
Copy the code

Or you can convert a string to an OC object to use OC’s methods

if toobjc(stringOne):isEqualToString('stringTwo') then
end
Copy the code

NSArray and NSDictionary cannot be used like normal objects in Lua because they are converted to tables by Wax. Instead, Lua uses tables for both. In Lua script, you cannot initialize Array or Dictionary.

NSMutableArray:init() 
NSMutableArray:arrayWithObjects("1"."2") 
NSMutableDictionary:init() 
NSMutableDictionary:dictionaryWithObjectsAndKeys("v1"."k1")
Copy the code

Initialization:

local array = {"a"."b"."c"}
Copy the code

Subscript access (note that Lua array subscripts all start at 1!) : Add elements:

table.insert(array, "d"Table. Insert (array, 2,"e"Table. Remove (array)-- remove the last element table. Remove (array, 2)-- remove the second elementCopy the code
Through:for i = 1, #array do
    print(array[i])
      end
for i, v in pairs(array) do- I as subscriptprint(v)
end
Copy the code

Self :muteArray():objectAtIndex(1) crashes Toobjc (self:muteArray()):objectAtIndex(1) correct

— — — — — — line — — — — — — — — — — — — line — — — — — — — — — — — — line — — — — — — — — — — — — line — — — — — –

String concatenation local URL =” string”.. “StringOther” calls class attributes such as array self:dataSource() to get the array length local count = table.getn(self:dataSource()); Set the textField keyboard type self: XTextField () : setKeyboardType (UIKeyboardTypeNumbersAndPunctuation); BOOL Initializes Local BOOOOOL = NSNumber:numberWithBool(true) Local dict = {keyOne=’value’,keyTwo= BOOOOOL} Assigns images to imageView Self :imageView():setImage(UIImage:imageNamed(“XXX”)) Gets the length of the string local strLength = string.len(string) based on the indexSection value local str = toobjc(self:rankArray()):objectAtIndex(indexPath:section())

Determines that a value is not nil

if XXX ~= nil
	then 	
        end
else
end
Copy the code

Layout method for navigation

local imageV = UIImageView:init()
self:view():addSubview(imageV)
toobjc(imageV):masUNDERxLINEmakeConstraints(
    toblock(
        function(make)
            make:top():equalTo()(toobjc(self: view()):masUNDERxLINEtop())
            make:bottom():equalTo()(toobjc(self: view()):masUNDERxLINEbottom())
            make:left():equalTo()(toobjc(self: view()):masUNDERxLINEleft())
            make:right():equalTo()(toobjc(self: view()):masUNDERxLINEright())
        end
        ,{'id'.'id'}))Copy the code
gsSetConfig({bind_ocf=true})
interface{"DZJMedicineDetailController"}

function getTimeCountDonwByStartDate(self,curDate)
if curDate == nil
then DZJToast:toast('Current time is empty')
return
end

localStartDate = NSDate:date() -- Add property self.timeInterval = toobjc(curDate):timeIntervalSinceDate(startDate);localCountDownTimer = NSTimer: scheduledTimerWithTimeInterval_block_repeats (1.0, toblock (function(timer)

if self.timeInterval <= 0
	then
		toobjc(sender):invalidate();
		setSender(nil)
		dispatch_async(dispatch_get_main_queue(),
			toblock(
				function( )
						self:loadCustomDataByFirstLoad(NO);
				end)
			);
else
	local days = math.floor((self.timeInterval/(3600*24)))
	local hours = math.floor(((self.timeInterval-days*24*3600)/3600));
	local minute = math.floor((self.timeInterval-days*24*3600-hours*3600)/60);
	local second = math.floor((self.timeInterval-days*24*3600-hours*3600-minute*60));
	dispatch_async(dispatch_get_main_queue(),
		toblock(
		function( )
			print('Mainline assignment')
			local tipLabel = toobjc(self:onlineTipView():subviews()):firstObject();
			print(tipLabel)
			local patientInfoText =  string.format("Live countdown :% 02D :% 02D :% 02D",(days*24+hours),minute,second)
			tipLabel:setText(patientInfoText)
		end)
	);
	self.timeInterval =  self.timeInterval - 1
end

		end),true);

end
Copy the code
function prepareForReuse(self)
	self.super:prepareForReuse(self);
	self:urgentImg():setImage(nil)
	self:imageBgView():removeAllSubviews();
end
Copy the code
if self:gotoMoreAction() ~= nil
     then						    
    gsCallBlockWithParamsType(self:gotoMoreAction(), {"void"."NSInteger"}, 7)
end
Copy the code