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


当前回答

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

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

其他回答

这是一个微妙但很方便的方法。如果你将自己作为委托传递给另一个对象,在dealloc之前重置该对象的委托。

- (void)dealloc
{
self.someObject.delegate = NULL;
self.someObject = NULL;
//
[super dealloc];
}

这样做可以确保不再发送更多的委托方法。当您即将dealloc并消失在以太中时,您希望确保没有任何东西可以意外地向您发送更多消息。还记得自己。someObject可以被另一个对象保留(它可以是一个单例对象或在自动释放池中或其他任何对象),直到您告诉它“停止向我发送消息!”,它才会认为您即将被释放的对象是公平的游戏。

养成这种习惯将使您避免大量令人痛苦的调试的奇怪崩溃。

同样的原理也适用于键值观察和NSNotifications。

编辑:

更有防御性的改变:

self.someObject.delegate = NULL;

成:

if (self.someObject.delegate == self)
    self.someObject.delegate = NULL;

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

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

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

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

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

@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

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

#import "MyClass.h"

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

@implementation MyClass