Một số tài liệu tham khảo:
- The Objective-C Programming Language
- Cocoa Fundamentals Guide
- Coding Guidelines for Cocoa
- iOS App Programming Guide
- Dot-Notation Syntax
- Spacing
- Conditionals
- Error handling
- Methods
- Variables
- Naming
- Comments
- Init
- Literals
- CGRect Functions
- Constants
- Enumerated Types
- Bitmasks
- Private Properties
- Image Naming
- Booleans
- Singletons
- Imports
Dot-notation nên luôn sử dụng set,get cho các thuộc tính. Các trường hợp còn lại thì sử dụng Bracket notation([])
Ví dụ:
view.backgroundColor = [UIColor orangeColor];
[UIApplication sharedApplication].delegate;
Not:
[view setBackgroundColor:[UIColor orangeColor]];
UIApplication.sharedApplication.delegate;
- Căn lề 4 khoảng trắng, ko bao giờ sử dụng phím tabs, thiết lập khoảng trắng này trong preference của xcode.
- Dấu ngoặc (
if
/else
/switch
/while
etc.) luôn luôn mở cùng dòng với câu lệnh và kết thúc ở dòng mới
Ví dụ:
if (user.isHappy) {
//Do something
}
else {
//Do something else
}
- Nên có dòng trống ngăn cách 2 method với nhau
@synthesize
và@dynamic
nên khai báo từng dòng cho mỗi cái khi implementation.
Nội dung Conditional luôn luôn đặt giữa 2 dấu ngoặc kể cả khi phần nội dung chỉ gồm 1 lệnh duy nhất.
Ví dụ:
if (!error) {
return success;
}
Not:
if (!error)
return success;
or
if (!error) return success;
Nên có khoảng trắng giữa ký hiệu (+/-) với tên method.
Ví dụ:
- (void)setExampleText:(NSString *)text image:(UIImage *)image;
Not:
-(void)setExampleText:(NSString *)text image:(UIImage *)image;
Tên biến nên đặt sao cho có ý nghĩa, tên biến với 1 chữ cái nên tránh trừ trường hợp trong vòng lặp for()
Dấu * thuộc về biến chứ không thuộc về kiểu giá trị của biến
ví dụ: NSString *text
not NSString* text
or NSString * text
, trừ trường hợp hằng số.
Apple naming conventions should be adhered to wherever possible, especially those related to memory management rules (NARC).
Long, descriptive method and variable names are good.
For example:
UIButton *settingsButton;
Not
UIButton *setBut;
A three letter prefix (e.g. NYT
) should always be used for class names and constants, however may be omitted for Core Data entity names. Constants should be camel-case with all words capitalized and prefixed by the related class name for clarity.
For example:
static const NSTimeInterval NYTArticleViewControllerNavigationFadeAnimationDuration = 0.3;
Not:
static const NSTimeInterval fadetime = 1.7;
Properties and local variables should be camel-case with the leading word being lowercase.
Instance variables should be camel-case with the leading word being lowercase, and should be prefixed with an underscore. This is consistent with instance variables synthesized automatically by LLVM. If LLVM can synthesize the variable automatically, then let it.
For example:
@synthesize descriptiveVariableName = _descriptiveVariableName;
Not:
id varnm;
When they are needed, comments should be used to explain why a particular piece of code does something. Any comments that are used must be kept up-to-date or deleted.
Block comments should generally be avoided, as code should be as self-documenting as possible, with only the need for intermittent, few-line explanations. This does not apply to those comments used to generate documentation.
init
methods nên được đặt ở đầu file thực thi ngay sau @synthesize và @dynamic, cấu trúc hàm init như sau:
- (instancetype)init {
self = [super init]; // or call the designated initializer
if (self) {
// Custom initializationsau
}
return self;
}
NSString
, NSDictionary
, NSArray
, và NSNumber
hằng số nên sử dụng khi tạo các immutable instances.
Ví dụ:
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 *buildingZIPCode = [NSNumber numberWithInteger:10018];
Khi truy cập x
, y
, width
, or height
of a CGRect
, luôn luôn sử dụng hàm CGGeometry
functions. Theo tài liệu của Apple:
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.
Ví dụ:
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;
Hằng nên được khai báo sử dụng static
constants không nên sử dụng #define
trừ trường hợp khai báo các Macro
Ví dụ:
static NSString * const NYTAboutViewControllerCompanyName = @"The New York Times Company";
static const CGFloat NYTImageThumbnailHeight = 50.0;
Not:
#define CompanyName @"The New York Times Company"
#define thumbnailHeight 2
Private properties nên được khai báo trong phần class extension của phần thực thi file của class.
For example:
@interface NYTAdvertisement ()
@property (nonatomic, strong) GADBannerView *googleAdView;
@property (nonatomic, strong) ADBannerView *iAdView;
@property (nonatomic, strong) UIWebView *adXWebView;
@end
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
andRefreshBarButtonItemSelected
/RefreshBarButtonItemSelected@2x
ArticleNavigationBarWhite
/ArticleNavigationBarWhite@2x
andArticleNavigationBarBlackSelected
/ArticleNavigationBarBlackSelected@2x
.
Images that are used for a similar purpose should be grouped in respective groups in an Images folder.
Không bao giờ so sánh 1 hàm hay 1 biến với 'YES', bởi vì 'YES' được định nghĩa là 1, và kiểu dữ liệu 'BOOL' thì có 8 bits
Ví dụ:
if (!someObject) {
}
Not:
if (someObject == nil) {
}
2 ví dụ về 'BOOL':
if (isAwesome)
if (![someObject boolValue])
Not:
if (isAwesome == YES) // Never do this.
if ([someObject boolValue] == NO)
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;
Text and example taken from the Cocoa Naming Guidelines.
Singleton objects nên sử dụng mẫu thread-safe để tạo 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.
If there is more than one import statement, group the statements together. Commenting each group is optional.
Note: For modules use the @import syntax.
// Frameworks
@import QuartzCore;
// Models
#import "NYTUser.h"
// Views
#import "NYTButton.h"
#import "NYTUserView.h"