如何在Objective-C中自动添加属性?

时间:2008-09-21 17:42:44

标签: objective-c properties

在向类中添加新属性时,我发现自己在xcode中反复输入相同的内容:

  1. add TYPE *NAME;(在.h界面中)
  2. add @property (nonatomic, retain) TYPE *NAME;(在.h)
  3. add @synthesize NAME;(在.m)
  4. add [NAME release];(在.m dealloc中)
  5. (我在非垃圾收集环境中。)

    我该如何自动执行此操作?

5 个答案:

答案 0 :(得分:1)

这听起来不错。 IIRC,Objective-C 2.0文档说你可以省略步骤#1,但我不知道有任何捷径。

您可以在Xcode中编写用户脚本。请参阅http://www.mactech.com/articles/mactech/Vol.23/23.01/2301XCode/index.html

答案 1 :(得分:1)

在64位运行时中

According to the Developer Documentation,您可以省略第1步。

答案 2 :(得分:0)

你可以看看Andrew Pang的RMModelObject - 我没有使用它,但它充当了一个简化模型创建的对象基类。

我没有使用它,但这里有一些自述文件中突出显示的内容:

  
      
  • 无需声明实例变量,
  •   
  • 无需编写访问器方法,
  •   
  • 免费的NSCopying协议支持(-copyWithZone:),
  •   
  • 免费的NSCoding协议支持(-initWithCoder:-encodeWithCoder:),
  •   
  • 免费-isEqual:和-hash`实施,
  •   
  • 在大多数情况下无需写-dealloc
  •   

答案 3 :(得分:0)

这是我修改过的另一个解决方案 this article(另见the initial article

博客中的版本是在变量声明块之外搜索变量,并且也匹配方法名称。我做了一个粗略的修复,只在第一个'}'之前搜索变量。如果头文件中有多个接口声明,则会中断。

我将输出设置为“Replace Document Conents”并输入为“Entire Document” ....

#!/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

答案 4 :(得分:0)

凯文卡拉汉的Accessorizer。从网页:

  

Accessorizer选择合适的   基于ivar类型的属性说明符    - 并且还可以自动生成显式访问器(1.0)......但是   Accessorizer做得更多,更多......