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

时间:2022-09-07 11:04:01

When adding new properties to classes, I find myself typing the same things over and over in xcode:

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

  1. add TYPE *NAME; (in .h interface)
  2. 添加TYPE * NAME; (在.h界面)

  3. add @property (nonatomic, retain) TYPE *NAME; (in .h)
  4. 添加@property(非原子,保留)TYPE * NAME; (在.h)

  5. add @synthesize NAME; (in .m)
  6. 添加@synthesize NAME; (在.m)

  7. add [NAME release]; (in .m dealloc)
  8. 添加[NAME发布]; (在.m dealloc中)

(I'm in a non-garbage collected environment.)

(我在非垃圾收集环境中。)

How can I do this automatically?

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

5 个解决方案

#1


1  

That sounds about right. IIRC, the Objective-C 2.0 doc says you might be able to leave out step #1, but otherwise I don't know of any shortcuts.

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

You could probably write a user script to do so within Xcode. See http://www.mactech.com/articles/mactech/Vol.23/23.01/2301XCode/index.html.

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

#2


1  

According to the Developer Documentation in 64bit runtimes you can leave out step 1.

根据64位运行时的开发人员文档,您可以省略第1步。

#3


0  

You could look at Andrew Pang's RMModelObject - I haven't used it, but it acts as a object base class that simplifies model creation.

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

I haven't used it, but here's some of what's highlighted in the readme:

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

  • no need to declare instance variables,
  • 无需声明实例变量,

  • no need to write accessor methods,
  • 无需编写访问器方法,

  • free NSCopying protocol support (-copyWithZone:),
  • 免费的NSCopying协议支持(-copyWithZone :),

  • free NSCoding protocol support (-initWithCoder:, -encodeWithCoder:),
  • 免费NSCoding协议支持(-initWithCoder:, - encodeWithCoder :),

  • free -isEqual: and -hash` implementation,
  • free -isEqual:和-hash`实现,

  • no need to write -dealloc in most cases.
  • 在大多数情况下,无需编写-dealloc。

#4


0  

Here's another solution which I modified from this article (also see the initial article)

这是我从本文修改的另一个解决方案(另见初始文章)

The version in the blog was searching for variables outside of the variable declaration block and was matching method names too. I have done a crude fix to only search for variables before the first '}'. This will break if there are multiple interface declarations in the header file.

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

I set the output to "Replace Document Conents" and input as "Entire Document" ....

我将输出设置为“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

#5


0  

There is Kevin Callahan's Accessorizer. From the web page:

还有凯文卡拉汉的配件。从网页:

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 ...

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

#1


1  

That sounds about right. IIRC, the Objective-C 2.0 doc says you might be able to leave out step #1, but otherwise I don't know of any shortcuts.

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

You could probably write a user script to do so within Xcode. See http://www.mactech.com/articles/mactech/Vol.23/23.01/2301XCode/index.html.

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

#2


1  

According to the Developer Documentation in 64bit runtimes you can leave out step 1.

根据64位运行时的开发人员文档,您可以省略第1步。

#3


0  

You could look at Andrew Pang's RMModelObject - I haven't used it, but it acts as a object base class that simplifies model creation.

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

I haven't used it, but here's some of what's highlighted in the readme:

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

  • no need to declare instance variables,
  • 无需声明实例变量,

  • no need to write accessor methods,
  • 无需编写访问器方法,

  • free NSCopying protocol support (-copyWithZone:),
  • 免费的NSCopying协议支持(-copyWithZone :),

  • free NSCoding protocol support (-initWithCoder:, -encodeWithCoder:),
  • 免费NSCoding协议支持(-initWithCoder:, - encodeWithCoder :),

  • free -isEqual: and -hash` implementation,
  • free -isEqual:和-hash`实现,

  • no need to write -dealloc in most cases.
  • 在大多数情况下,无需编写-dealloc。

#4


0  

Here's another solution which I modified from this article (also see the initial article)

这是我从本文修改的另一个解决方案(另见初始文章)

The version in the blog was searching for variables outside of the variable declaration block and was matching method names too. I have done a crude fix to only search for variables before the first '}'. This will break if there are multiple interface declarations in the header file.

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

I set the output to "Replace Document Conents" and input as "Entire Document" ....

我将输出设置为“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

#5


0  

There is Kevin Callahan's Accessorizer. From the web page:

还有凯文卡拉汉的配件。从网页:

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 ...

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