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


当前回答

@kendell

而不是:

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

Use:

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

Objective-C 2.0新功能。

Apple的Objective-C 2.0参考中描述了类扩展。

类扩展允许你在主类@interface块之外的位置为类声明额外的必需API

所以它们是实际类的一部分——而不是类之外的(私有)类别。细微但重要的区别。

其他回答

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

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

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

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

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

在dealloc中清理。

这是最容易忘记的事情之一——尤其是在以150英里/小时的速度编码时。总是,总是,总是清理dealloc中的属性/成员变量。

我喜欢使用Objc 2属性-新的点表示法-所以这使得清理变得无痛。通常很简单:

- (void)dealloc
{
    self.someAttribute = NULL;
    [super dealloc];
}

这将为您处理发布,并将属性设置为NULL(我认为这是防御性编程——以防dealloc中的另一个方法再次访问成员变量——很少,但也可能发生)。

在10.5中打开GC后,就不再需要这么多了——但是你可能仍然需要清理你创建的其他资源,你可以在finalize方法中做这件事。

打开所有GCC警告,然后关闭那些通常由Apple头文件引起的警告,以减少噪音。

还经常运行叮当静态分析;您可以通过“运行静态分析器”构建设置为所有构建启用它。

编写单元测试,并在每次构建时运行它们。

功能性更强。

Objective-C是面向对象的语言,但是Cocoa框架是函数式风格的,并且在很多情况下是函数式设计的。

There is separation of mutability. Use immutable classes as primary, and mutable object as secondary. For instance, use NSArray primarily, and use NSMutableArray only when you need. There is pure functions. Not so many, buy many of framework APIs are designed like pure function. Look at functions such as CGRectMake() or CGAffineTransformMake(). Obviously pointer form looks more efficient. However indirect argument with pointers can't offer side-effect-free. Design structures purely as much as possible. Separate even state objects. Use -copy instead of -retain when passing a value to other object. Because shared state can influence mutation to value in other object silently. So can't be side-effect-free. If you have a value from external from object, copy it. So it's also important designing shared state as minimal as possible.

但是也不要害怕使用不纯函数。

There is lazy evaluation. See something like -[UIViewController view] property. The view won't be created when the object is created. It'll be created when caller reading view property at first time. UIImage will not be loaded until it actually being drawn. There are many implementation like this design. This kind of designs are very helpful for resource management, but if you don't know the concept of lazy evaluation, it's not easy to understand behavior of them. There is closure. Use C-blocks as much as possible. This will simplify your life greatly. But read once more about block-memory-management before using it. There is semi-auto GC. NSAutoreleasePool. Use -autorelease primary. Use manual -retain/-release secondary when you really need. (ex: memory optimization, explicit resource deletion)