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


当前回答

避免生成

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

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

其他回答

不要使用未知字符串作为格式字符串

当方法或函数接受格式字符串参数时,应确保能够控制格式字符串的内容。

例如,当记录字符串时,很容易将字符串变量作为唯一参数传递给NSLog:

    NSString *aString = // get a string from somewhere;
    NSLog(aString);

这样做的问题是,字符串可能包含被解释为格式字符串的字符。这可能导致错误的输出、崩溃和安全问题。相反,你应该将字符串变量替换为一个格式字符串:

    NSLog(@"%@", aString);

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

self.<property> = nil;

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

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

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

@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;
}   

使用LLVM/Clang静态分析仪

注意:在Xcode 4中,这是内置在IDE中。

你可以使用Clang Static Analyzer在Mac OS X 10.5上分析你的C和Objective-C代码(还没有c++)。安装和使用起来很简单:

从本页下载最新版本。 从命令行,cd到您的项目目录。 执行scan-build -k -V xcodebuild。

(还有一些额外的限制等等,特别是你应该在“调试”配置中分析一个项目——详情请参阅http://clang.llvm.org/StaticAnalysisUsage.html——但这或多或少就是它的总结。)

分析器然后为您生成一组网页,显示可能的内存管理和编译器无法检测的其他基本问题。

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