如何给quick-cocos2d-x的model类自动添加get和set函数
对于model类,如果比较正式的话,访问属性应当采用get和set的方式,当该类属性比较多,而且大量都是直接读取时,增加一个自动生成get和set函数的操作
就会比较方便,这样只需要针对特殊的属性单独写get和set即可 1.首先先简单说明一下如何给类动态定义成员函数名 lua的函数名是可以动态配置的
2.下面说一下如何生成set和get函数 注意该函数只适用于从quick cocos2dx中mvc框架的cc.mvc.ModelBase类派生,而且采用schema定义属性的情况 --自动添加get和set函数 local function initGetterAndSetter(target) if target.schema and type(target.schema)=="table" and #target.schema then for field,typ in pairs(target.schema) do --首字母变大写 local uname = string.ucfirst(field) local gfname = "get"..uname) --如果代码没有特殊写该属性的get函数,则自动生成 if (not target[gfname]) then target[gfname] = function(target) return target[field.."_"] end end local sfname = "set"..uname local vtype = typ if type(typ) == "table" then vtype = typ[1] end --如果代码没有特殊写该属性的set函数,则自动生成 if (not target[sfname]) then target[sfname] = function(target,value) if value == nil then return end if vtype == "string" then value = tostring(value) elseif vtype == "number" then value = checknumber(value) end if type(value) == vtype then target[field.."_"] = value end end end end end end 在该类的构造函数中调用,例如 function TestModel:ctor(properties) TestModel.super.ctor(self,properties) initGetterAndSetter(self) end 假设属性为 TestModel2.schema["sizex"] = {"number",0} 就会自动生成 getSizex函数和setSizex函数 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |