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


当前回答

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

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

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

其他回答

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

self.<property> = nil;

避免生成

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方法)。

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

使用NSAssert和朋友。 我一直使用nil作为有效对象…特别是发送消息给nil在Obj-C中是完全有效的。 然而,如果我真的想确定一个变量的状态,我使用NSAssert和NSParameterAssert,这有助于轻松跟踪问题。

简单但经常被遗忘。根据规格:

一般来说,方法各不相同 具有相同选择器的类 (相同的名字)也必须共享 相同的返回值和参数类型。这 约束是由编译器施加的 允许动态绑定。

在这种情况下,所有相同的命名选择器,即使在不同的类中,也会被认为具有相同的返回/参数类型。这里有一个简单的例子。

@interface FooInt:NSObject{}
-(int) print;
@end

@implementation FooInt
-(int) print{
    return 5;
}
@end

@interface FooFloat:NSObject{}
-(float) print;
@end

@implementation FooFloat
-(float) print{
    return 3.3;
}
@end

int main (int argc, const char * argv[]) {

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];    
    id f1=[[FooFloat alloc]init];
    //prints 0, runtime considers [f1 print] to return int, as f1's type is "id" and FooInt precedes FooBar
    NSLog(@"%f",[f1 print]);

    FooFloat* f2=[[FooFloat alloc]init];
    //prints 3.3 expectedly as the static type is FooFloat
    NSLog(@"%f",[f2 print]);

    [f1 release];
    [f2 release]
    [pool drain];

    return 0;
}   

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

更新:除非你正在使用ARC