如何在Objective-C中自动添加属性?
时间:2020-03-06 14:30:39 来源:igfitidea点击:
当向类添加新属性时,我发现自己在xcode中一遍又一遍地键入相同的内容:
add TYPE * NAME;
(在.h界面中)add @property(nonatomic,保留)TYPE * NAME;
(在.h中)add @synthesize NAME;
(在.m中)add [NAME release];
(在.m dealloc中)
(我处于非垃圾收集环境中。)
如何自动执行此操作?
解决方案
听起来不错。 IIRC,Objective-C 2.0文档说我们可以省去第1步,但否则我不知道任何捷径。
我们可能可以在Xcode中编写一个用户脚本来这样做。参见http://www.mactech.com/articles/mactech/Vol.23/23.01/2301XCode/index.html。
根据64位运行时中的开发人员文档,我们可以省去步骤1.
我们可以看一下我尚未使用过的Andrew Pang的RMModelObject,但它充当了简化模型创建的对象基类。
我没有使用过,但是这是自述文件中突出显示的一些内容:
no need to declare instance variables, no need to write accessor methods, free NSCopying protocol support (-copyWithZone:), free NSCoding protocol support (-initWithCoder:, -encodeWithCoder:), free -isEqual: and -hash` implementation, no need to write -dealloc in most cases.
这是我修改的另一个解决方案
本文(另请参阅初始文章)
博客中的版本正在变量声明块之外搜索变量,并且也在匹配方法名称。我已经做了一个粗略的修正,只搜索第一个'}'之前的变量。如果头文件中有多个接口声明,这将中断。
我将输出设置为"替换文档内容",并输入为"整个文档"
....
#!/usr/bin/python thisfile = '''%%%{PBXFilePath}%%%''' code = '''%%%{PBXAllText}%%%''' selmark = '''%%%{PBXSelection}%%%''' import re if thisfile.endswith('.h'): variableEnd = code.find('\n', code.find('}')) properties = [] memre = re.compile('\s+(?:IBOutlet)?\s+([^\-+@].*? \*?.*?;)') for match in memre.finditer(code[:variableEnd]): member = match.group(1) retain = member.find('*') != -1 and ', retain' or '' property = '@property (nonatomic%s) %s' % (retain,member) if code.find(property) == -1: properties.append(property) if properties: print '%s\n\n%s%s%s%s' % (code[:variableEnd],selmark,'\n'.join(properties),selmark,code[variableEnd:]) elif thisfile.endswith('.m'): headerfile = thisfile.replace('.m','.h') properties = [] retains = [] propre = re.compile('@property\s\((.*?)\)\s.*?\s\*?(.*?);') header = open(headerfile).read() for match in propre.finditer(header): if match.group(1).find('retain') != -1: retains.append(match.group(2)) property = '@synthesize %s;' % match.group(2) if code.find(property) == -1: properties.append(property) pindex = code.find('\n', code.find('@implementation')) if properties and pindex != -1: output = '%s\n\n%s%s%s' % (code[:pindex],selmark,'\n'.join(properties),selmark) if retains: dindex = code.find('\n', code.find('(void)dealloc')) output += code[pindex:dindex] retainsstr = '\n\t'.join(['[%s release];' % retain for retain in retains]) output += '\n\t%s' % retainsstr pindex = dindex output += code[pindex:] print output
有Kevin Callahan的Accessorizer。在网页上:
Accessorizer selects the appropriate property specifiers based on ivar type - and can also generate explicit accessors (1.0) automagically ... but Accessorizer does much, much more ...