Fork me on GitHub

[iOS] Objective C 编程规范

格式化代码

1.指针“*”号的位置?如:NSString *varName;

贴近变量名称,一行只能定义一个变量,不允许定义多个变量。

2. 空格VS tabs?

使用tab,一个tab设定为4个空格

3.每行的长度?

每行最多不得超过100个字,不是古老的80个字符。Xcode => Preferences => TextEditing => Page Guide at column /输入 100即可

 

方法的声明和定义

1.- OR +和返回值之间留1个空格,方法名和第一个参数间不留空格。如:

- (void)doSomethingWithString:(NSString *)theString

{

...

}

标识参数类型的星号前面有个space。

2.当参数过长时,每个参数占用一行,以冒号对齐。如:

 

- (void)doSomethingWith:(GTMFoo *)theFoo

         rect:(NSRect)theRect

         interval:(float)theInterval

{

...

}

3. 方法的调用

调用方法沿用声明方法的习惯。

4.@public@private

权限控制符@public@private不缩进,顶着左边写。

5.Protocols

型标示符、代理名称、尖括号间不留空格。

 

@interface MyProtocoledClass : NSObject<NSWindowDelegate>

{

@private

id<MyFancyDelegate> _delegate;

}

- (void)setDelegate:(id<MyFancyDelegate>)aDelegate;

@end

6. 异常

每个异常标签的@和开括号({)分开两行写,同样适用于@catch语句。

@try

{

foo();

}

@catch (NSException *ex)

{

bar(ex);

}

@finally

{

baz();

}

7. Blocks

Blocks are preferred to the target-selector pattern when creating callbacks, as it makes code easier to read. Code inside blocks should be indented four spaces.

There are several appropriate style rules, depending on how long the block is:

  • If the block can fit on one line, no wrapping is necessary.
  • If it has to wrap, the closing brace should line up with the first character of the line on which the block is declared.
  • Code within the block should be indented four spaces.
  • If the block is large, e.g. more than 20 lines, it is recommended to move it out-of-line into a local variable.
  • If the block takes no parameters, there are no spaces between the characters ^{. If the block takes parameters, there is no space between the ^( characters, but there is one space between the ) { characters.
  • Two space indents inside blocks are also allowed, but should only be used when it's consistent with the rest of the project's code.
// The entire block fits on one line.[operation setCompletionBlock:^{ [self onOperationDone]; }];



Part 1: basics on naming classes, variables, accessors, general methods and abbreviations.


1. Putting Thought into Naming 取名表意


cocoa建议是明确,清晰和没有歧义的名字。 



2. Class Names


类名要大写,加上前缀 



3. Variable Names


小写开头,内部单词大写。私有的实例变量不要用下划线来开头。



4. Variable Names: Indicating Type


变量名字通常不会反映他的类型,特别是NSString,NSArray,BOOL等,此处的命名没有必要在变量名字后面加上String等后缀。对于一些其他非基础类型的可以加上后缀来表明,比如:NSImage,NSFontManager等。



5. Method Names


choosing a method name based on how it will look in actual use



6. Method Names: Accessors


Objective-Cdiscourages use of the "get" prefix on simple accessors. Instance variables and methods can have the same name.


对于非名词的属性,比如形容词,可以用isEditable来描述。


7. Abbreviations


工业标准的缩写全用大写,比如:JPEG,XML,URL。编程相关的用小写:int,rect,max等。编译预处理的的常量和字符串全部用大写。



Part 2: more detail on method names, global symbols, the id type, method parameters, etc


 


1. Method Names: Returning Objects


[object/classthing+condition];


[object/classthing+input:input];


[object/classthing+identifer:input];


 


Sometimes, you want a variation on a value. In that case, the format is generally:


[object adjective+thing];


[object adjective+thing+condition];


[object adjective+thing+input:input];



2. Avoid Ambiguity


-currentSortInfo // "current" obviously describes the noun "sort info"


-refreshDefaultTimer // refresh is now clearly a verb


-updateMenuItemTitle// an action is taking place


-infoForFetch: // now we know info is returned for a fetch



3. Global C Functions


Prefix +Value()


Prefix +Value+ With/From/For +Input()


Prefix +Action()


Prefix +Action+Type()


NSHomeDirectory()


NSHomeDirectoryForUser()


NSClassFromString()


NSBeginAlertSheet()


NSDrawGrayBezel()



4. Other Global Symbols


  • Constants
  • Typedef'd structs
  • Typedef'd enums
  • Individual enum values
  • Objective-C Protocols

Both constants and enums have a suffix that indicates what kind of thing they are:


//searchmodes (enums)


NSLiteralSearch


NSCaseInsensitiveSearch


//exceptionnames (constants)


NSMallocException


NSInvalidArgumentException


//notificationnames (constants)


NSTaskDidTerminateNotification


NSWindowWillMoveNotification


Class of Affected Object+ Did/Will + Action +"Notification"



5. Dynamic Typing


So why specify type at all? Three basic reasons:


  1. To be clear: Makes it clear what you intend to do with the variable
  2. To avoid uselesswarnings: If multiple classes share the same method name, the compiler may warn you when you send that message to a generic object.
  3. To get usefulwarnings: If you mispell a message name, such as "-stringg", the compiler will tell you that NSMutableString does not implement such a method

In addition, there are situations where theidtype makes the most sense. Some are:


  1. A delegate or datasource
  2. Object for a notification
  3. Contents for a generic container
  4. Objects involved in target/action

So no hard rules here, but a good basic practice is to specify the type if you have reason to believe other types of objects wouldn't make sense in a given situation.


Objective-C is a dynamically-typed language, meaning that you don't have to tell the compiler what type of object you're working with at compile time. 



6.When to Use Accessors


Short answer: always


 


7.Naming Parameters


The guidelines are considerably more loose, but typically you prefix the input name with "the", "an" or "new"


 


8. Odds and Ends


If you're sending a message with a particularly long name, break it up into multiple lines.


Classes that return one and only one instance of themselves (singletons) are named and implemented as follows.


posted on 2012-02-08 17:28  pengyingh  阅读(969)  评论(0)    收藏  举报

导航