我喜欢并使用的一种规范
大部分采取纽约时报iOS团队的编码规范,结合自己的一些习惯
Dot-Notation Syntax
Dot-notation should always be used for accessing and mutating properties. Bracket notation is preferred in all other instances.
For example:
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
Not:
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;
关于if / else / switch / for / enum / while等,这些语句,我还是使用自己一直书写的方式
Conditionals
Conditional bodies should always use braces even when a conditional body could be written without braces (i.e., it is one line only) braces should still be used. There are just too many little ways to get burned otherwise.
For example:
if (!error) {
return success;
}
Not:
if (!error)
return success;
or
if (!error) return success;
Methods
In method signatures, there should be a space after the scope (-/+ symbol). There should be a space between the method segments.
For Example:
- (
void
)
setExampleText:
(NSString *)
text
image:
(UIImage *)
image
;
Variables
Variables should be named as descriptively as possible. Single letter variable names should be avoided except in
for()
loops.
Asterisks indicating pointers belong with the variable, i.e.
NSString *text
not
NSString* text
or
NSString * text
, except in the case of constants.
Property definitions should be used in place of naked instance variables whenever possible. Direct instance variable access should be avoided except in initializer methods (
init
,
initWithCoder:
, etc…),
dealloc
methods and within custom setters and getters. For more information on using Accessor Methods in Initializer Methods and dealloc, see
here
.
For example:
@interface
NYTSection
:
NSObject
@property (nonatomic) NSString *headline;
@end
Not:
@interface
NYTSection
:
NSObject
{
NSString *headline;
}
init and dealloc
dealloc
methods should be placed at the top of the implementation, directly after the
@synthesize
and
@dynamic
statements.
init
should be placed directly below the
dealloc
methods of any class.
Literals
NSString
,
NSDictionary
,
NSArray
, and
NSNumber
literals should be used whenever creating immutable instances of those objects. Pay special care that
nil
values not be passed into
NSArray
and
NSDictionary
literals, as this will cause a crash.
For example:
NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
NSDictionary *productManagers = @{@"iPhone" : @"Kate", @"iPad" : @"Kamal", @"Mobile Web" : @"Bill"};
NSNumber *shouldUseLiterals = @YES;
NSNumber *buildingZIPCode = @10018;
Not:
NSArray *names = [NSArray arrayWithObjects:@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul", nil];
NSDictionary *productManagers = [NSDictionary dictionaryWithObjectsAndKeys: @"Kate", @"iPhone", @"Kamal", @"iPad", @"Bill", @"Mobile Web", nil];
NSNumber *shouldUseLiterals = [NSNumber numberWithBool:YES];
NSNumber *ZIPCode = [NSNumber numberWithInteger:10018];
CGRect Functions
When accessing the
x
,
y
,
width
, or
height
of a
CGRect
, always use the
CGGeometry
functions
instead of direct struct member access. From Apple's
CGGeometry
reference:
All functions described in this reference that take CGRect data structures as inputs implicitly standardize those rectangles before calculating their results. For this reason, your applications should avoid directly reading and writing the data stored in the CGRect data structure. Instead, use the functions described here to manipulate rectangles and to retrieve their characteristics.
For example:
CGRect frame = self.view.frame;
CGFloat x = CGRectGetMinX(frame);
CGFloat y = CGRectGetMinY(frame);
CGFloat width = CGRectGetWidth(frame);
CGFloat height = CGRectGetHeight(frame);
Not:
CGRect frame = self.view.frame;
CGFloat x = frame.origin.x;
CGFloat y = frame.origin.y;
CGFloat width = frame.size.width;
CGFloat height = frame.size.height;
Enumerated Types
When using
enum
s, it is recommended to use the new fixed underlying type specification because it has stronger type checking and code completion. The SDK now includes a macro to facilitate and encourage use of fixed underlying types —
NS_ENUM()
Example:
typedef
NS_ENUM
(NSInteger, NYTAdRequestState) {
NYTAdRequestStateInactive,
NYTAdRequestStateLoading
};
Private Properties
Private properties should be declared in class extensions (anonymous categories) in the implementation file of a class. Named categories (such as
NYTPrivate
or
private
) should never be used unless extending another class.
For example:
@interface
NYTAdvertisement
()
@property (nonatomic, retain) GADBannerView *googleAdView;
@property (nonatomic, retain) ADBannerView *iAdView;
@property (nonatomic, retain) UIWebView *adXWebView;
@end
Image Naming
Image names should be named consistently to preserve organization and developer sanity. They should be named as one camel case string with a description of their purpose, followed by the un-prefixed name of the class or property they are customizing (if there is one), followed by a further description of color and/or placement, and finally their state.
For example:
RefreshBarButtonItem
/
RefreshBarButtonItem@2x
and
RefreshBarButtonItemSelected
/
RefreshBarButtonItemSelected@2x
ArticleNavigationBarWhite
/
ArticleNavigationBarWhite@2x
and
ArticleNavigationBarBlackSelected
/
ArticleNavigationBarBlackSelected@2x
.
Images that are used for a similar purpose should be grouped in respective groups in an Images folder.
Booleans
Since
nil
resolves to
NO
it is unnecessary to compare it in conditions. Never compare something directly to
YES
, because
YES
is defined to 1 and a
BOOL
can be up to 8 bits.
This allows for more consistency across files and greater visual clarity.
For example:
if (!someObject) {
}
Not:
if (someObject ==
nil
) {
}
For a BOOL, here's two examples:
if (isAwesome)
if (![someObject boolValue])
Not:
if ([someObject boolValue] ==
NO
)
if (isAwesome ==
YES
)
// Never do this.
If the name of a BOOL property is expressed as an adjective, the property can omit the “is” prefix but specifies the conventional name for the get accessor, for example:
@property (assign, getter=isEditable)
BOOL
editable;
Singletons
Singleton objects should use a thread-safe pattern for creating their shared instance.
+ (instancetype)sharedInstance {
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
This will prevent
possible and sometimes prolific crashes
.