我知道HIG(这非常方便!),但是在编写Objective-C时,更具体地说,在使用Cocoa(或CocoaTouch)时,您使用了什么编程实践?


当前回答

根据用户需要对字符串进行排序

在对要呈现给用户的字符串进行排序时,不应该使用简单的compare:方法。相反,你应该总是使用本地化比较方法,如localizedCompare:或localizedcaseinsensitiveecompare:。

有关详细信息,请参见搜索、比较和排序字符串。

其他回答

避免生成

Since you typically(1) don't have direct control over their lifetime, autoreleased objects can persist for a comparatively long time and unnecessarily increase the memory footprint of your application. Whilst on the desktop this may be of little consequence, on more constrained platforms this can be a significant issue. On all platforms, therefore, and especially on more constrained platforms, it is considered best practice to avoid using methods that would lead to autoreleased objects and instead you are encouraged to use the alloc/init pattern.

因此,而不是:

aVariable = [AClass convenienceMethod];

在可能的情况下,你应该使用:

aVariable = [[AClass alloc] init];
// do things with aVariable
[aVariable release];

当您编写自己的方法返回新创建的对象时,您可以利用Cocoa的命名约定,通过在方法名前加上“new”来标记接收方必须释放该对象。

因此,与其:

- (MyClass *)convenienceMethod {
    MyClass *instance = [[[self alloc] init] autorelease];
    // configure instance
    return instance;
}

你可以这样写:

- (MyClass *)newInstance {
    MyClass *instance = [[self alloc] init];
    // configure instance
    return instance;
}

因为方法名以"new"开头,你的API的使用者知道他们负责释放接收到的对象(例如,看NSObjectController的newObject方法)。

你可以通过使用你自己的本地自动释放池来控制。有关这方面的更多信息,请参见自动释放池。

抵制世界的子类化。在Cocoa中,很多工作都是通过委托和使用底层运行时完成的,而在其他框架中则是通过子类化完成的。

例如,在Java中你经常使用匿名*Listener子类的实例,在. net中你经常使用EventArgs子类。在Cocoa中,你什么都不用做——而是使用目标-动作。

还有一个半相关的话题(还有更多的回复空间!):

有哪些Xcode的小技巧和技巧是你希望2年前就知道的?

黄金法则:如果你分配了,那么你就释放了!

更新:除非你正在使用ARC

所有这些评论都很棒,但我真的很惊讶没有人提到谷歌的Objective-C风格指南,这是不久前发布的。我认为他们做得很彻底。