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


当前回答

对于初学者来说,一个很明显的方法是:利用Xcode的自动缩进功能。即使是从其他源复制/粘贴代码,粘贴完代码后,也可以选择整个代码块,右键单击它,然后选择选项重新缩进该代码块中的所有内容。

Xcode会解析这个section并根据括号,循环等缩进它。这比每一行都按空格键或tab键要有效率得多。

其他回答

声明属性

对于所有属性,您通常应该使用Objective-C 2.0声明属性特性。如果它们不是公共的,将它们添加到类扩展中。使用声明的属性使内存管理语义立即清晰,并使您更容易检查dealloc方法——如果您将属性声明分组在一起,您可以快速扫描它们并与dealloc方法的实现进行比较。

在不将属性标记为“nonatomic”之前,您应该仔细考虑一下。正如《Objective C编程语言指南》所指出的,属性在默认情况下是原子的,并且会产生相当大的开销。此外,简单地将所有属性都设置为原子化并不能使应用程序具有线程安全性。当然,还要注意,如果你没有指定“nonatomic”,并且实现你自己的访问方法(而不是合成它们),你必须以原子的方式实现它们。

只释放dealloc方法中的属性。如果你想释放属性所持有的内存,只需将其设置为nil:

self.<property> = nil;

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

更新:除非你正在使用ARC

#import "MyClass.h"

@interface MyClass ()
- (void) someMethod;
- (void) someOtherMethod;
@end

@implementation MyClass

使用标准的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平台时放弃了这一点。