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


当前回答

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

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

其他回答

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

更新:除非你正在使用ARC

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

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

IBOutlets

从历史上看,outlet的内存管理一直很差。 当前的最佳实践是将outlet声明为属性:

@interface MyClass :NSObject {
    NSTextField *textField;
}
@property (nonatomic, retain) IBOutlet NSTextField *textField;
@end

使用属性使内存管理语义清晰;如果使用实例变量综合,它还提供了一致的模式。

使用标准的Cocoa命名和格式化约定和术语,而不是使用其他环境中使用的任何术语。有很多Cocoa开发人员,当他们中的另一个人开始使用您的代码时,如果它看起来和感觉上与其他Cocoa代码相似,那么它将更容易接近。

做什么和不做什么的例子:

Don't declare id m_something; in an object's interface and call it a member variable or field; use something or _something for its name and call it an instance variable. Don't name a getter -getSomething; the proper Cocoa name is just -something. Don't name a setter -something:; it should be -setSomething: The method name is interspersed with the arguments and includes colons; it's -[NSObject performSelector:withObject:], not NSObject::performSelector. Use inter-caps (CamelCase) in method names, parameters, variables, class names, etc. rather than underbars (underscores). Class names start with an upper-case letter, variable and method names with lower-case.

无论你做什么,不要使用Win16/ win32风格的匈牙利符号。甚至微软也在转向。net平台时放弃了这一点。

我看到的苹果提供的示例将App委托视为一个全局数据存储,一种数据管理器。这是错误的。创建一个单例,并在App委托中实例化它,但不要将App委托用作应用程序级事件处理以外的任何东西。我衷心赞同这篇博客文章中的建议。这条线索暴露了我。