Mat*_*ing 20 cocoa cocoa-touch objective-c naming-conventions
继承其他开发人员的代码使我坚信通过类扩展从类的公共接口中保留尽可能多的消息.我也坚信为类的特定于实现的私有成员采用特殊的命名约定.我真的希望能够一目了然地告诉我们发送的消息以及在实现环境中被引用的成员是不是供公众使用,反之亦然.如果没有别的,它会使我更容易掌握一个班级的整体语义,这是值得的.
理由之外,我写的类容载有容载量2的私有方法,但我从来没有真正拿出一个模式来命名,我真的很喜欢(像我做的ivars争议ivar_约定).值得注意的例子:
@interface myClass()
// I like this, but as we all know, Apple has dibs on this one,
// and method name collisions are nasty.
- (void)_myPrivateMessage;
// The suffix version promoted by Google for ivars doesn't really translate
// well to method names in Objective-C, because of the way the method
// signature can be broken into several parts.
- (void)doWork_; // That's okay...
- (void)doWork_:(id)work with_:(id)something; // That's just ugly and tedious...
- (void)doWork_:(id)work with_:(id)something and_:(id)another; // My eyes...
// This version is suggested by Apple, and has the benefit of being officially
// recommended. Alas, I don't like it: The capital letter is ugly. I don't like
// underscores in the middle of the name. Worst of all, I have to type three characters
// before code-sense does anything more useful than inform me that I am typing.
- (void)BF_doWork;
@end
Run Code Online (Sandbox Code Playgroud)
在这一点上,我有一种不同的手段可以破坏我的私人方法名称,但我没有做出什么,我想我会首先对我可能不知道的任何流行惯例进行民意调查.那么,你用过什么?
我没有按名称区分私人方法.相反,我通过在.m文件的类扩展部分声明它们使它们脱离公共接口,因此:
@interface MyClass ()
- (void)doWork;
@end
Run Code Online (Sandbox Code Playgroud)
小智 7
我为我的私有方法使用双下划线:
- (void)__doSomethingPrivate;
Run Code Online (Sandbox Code Playgroud)
它几乎看起来像单个下划线语法(良好的可读性),同时向Apple指南确认.
我使用两个级别的私有方法:轻微私有和非常私有。轻微私有方法是可以公开的方法,但目前还没有。它们通常是我在内部使用的便捷方法,除非我决定将其公开,否则我通常不会提供太多的保护。对于非常私有的方法,我忽略 apple 并使用下划线前缀。由于我 99% 的代码都在我创建的类中,并且我的类名通常有前缀,因此遇到命名问题的可能性很小。当向我没有创建的类添加代码时,我很少创建私有方法,但在极少数情况下会添加一个短前缀。