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


当前回答

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

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

其他回答

想想nil值

正如这个问题所指出的,到nil的消息在Objective-C中是有效的。虽然这通常是一个优势——导致更干净和更自然的代码——但如果您在意想不到的情况下获得nil值,该功能偶尔会导致特殊且难以追踪的错误。

功能性更强。

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)

还有一个半相关的话题(还有更多的回复空间!):

有哪些Xcode的小技巧和技巧是你希望2年前就知道的?

尽量避免我现在决定称之为“新类别yaholism”的现象。当Objective-C的新手发现类别时,他们通常会疯狂地为现有的每个类添加有用的小类别(“什么?我可以添加一个方法来转换一个数字到罗马数字到NSNumber岩石上!”)。

不要这样做。

你的代码将更容易移植,更容易理解,因为没有几十个小类别方法散布在20多个基础类之上。

大多数时候,当你真的认为你需要一个类别方法来帮助简化一些代码时,你会发现你永远不会重用这个方法。

还有其他的危险,除非你对你的分类方法进行命名空间(除了疯狂的ddribin,还有谁会这么做呢?),在你的地址空间中运行的苹果、插件或其他东西也有可能用相同的名称定义相同的分类方法,但副作用略有不同....

好的。现在你已经被警告过了,忽略“不要做这部分”。但是要极度克制。

编写单元测试。您可以在Cocoa中测试许多在其他框架中可能比较困难的事情。例如,对于UI代码,您通常可以验证事物是否按照应有的方式连接,并相信它们在使用时能够正常工作。你可以很容易地设置状态和调用委托方法来测试它们。

在编写内部测试时,也不会有公共、受保护和私有方法可见性。