Some guidelines for writing statements and variables in Objective C programming are recommended

  • 2020-05-27 07:14:37
  • OfStack

Conditional statements

The conditional body should always be surrounded by braces. Only 1 line of code had better be added, otherwise it will cause a security hazard.

// recommended
if (!error) {
    return success;
} // Is not recommended
if (!error)
    return success; if (!error) return success;

Yoda expression (Yoda)

Do not use yoda expressions. (the name comes from yoda's way of speaking in Star Wars, always in reverse order.)

// recommended
if ([myValue isEqual:@42]) { ... // Is not recommended
if ([@42 isEqual:myValue]) { ...

Inspection of nil and BOOL

1 some people like to check nil in this way:

if (nil == myValue) { ...

This avoids one less "= "error, because if one fewer "=" is written, nil will not be assigned, and the compiler will report an error.

But as mentioned earlier, it's best not to use yoda expressions. So a better solution is to use "!" To complete the nil and BOOL checks.

// recommended
if (someObject) { ...
if (![someObject boolValue]) { ...
if (!someObject) { ... // Is not recommended
if (someObject == YES) { ... // Wrong
if (myRawValue == YES) { ... // Never do this.
if ([someObject boolValue] == NO) { ...

Do not nest multiple if statements

Instead of nesting multiple if statements, use multiple return statements to avoid complexity and improve code readability.

That is, in a method, try not to put the important part in the if statement, but put the "other case" in if.

// recommended
- (void)someMethod {
  if (![someOther boolValue]) {
  }   //Do something important
} // Is not recommended
- (void)someMethod {
  if ([someOther boolValue]) {
    //Do something important

Complex expression

When a judgment condition is complex, it should be extracted and assigned to an BOOL variable.

BOOL nameContainsSwift  = [sessionName containsString:@"Swift"];
BOOL isCurrentYear      = [sessionDateCompontents year] == 2014;
BOOL isSwiftSession     = nameContainsSwift && isCurrentYear; if (isSwiftSession) {
    // Do something very cool

The 3 meta operator

The 3 meta operator ensures readability.

// recommended
result = a > b ? x : y; // Is not recommended
result = a > b ? x = c > d ? c : d : y;

When the second argument of the 3 meta-operator (if branch) returns an object like the one already checked in the conditional statement, the following expression is more clever:

// recommended
result = object ? : [self createObject]; // Is not recommended
result = object ? object : [self createObject];

Error handling

When using a method that returns a reference to error via a parameter, you should check the return value of the method, not the error reference.

// recommended
NSError *error = nil;
if (![self trySomethingWithError:&error]) {
    // Handle Error

case in switch statement, if there is only 1 line of code, you don't need curly braces, but multiple lines do.

switch (condition) {
    case 1:
        // ...
    case 2: {
        // ...
        // Multi-line example using braces
    case 3:
        // ...
        // ...

Enumerated type

Enums are defined using the NS_ENUM() macro, which has more powerful type checking and code completion.

typedef NS_ENUM(NSUInteger, ZOCMachineState) {

Use long, descriptive methods and variable names whenever possible.

// recommended
UIButton *settingsButton; // Is not recommended
UIButton *setBut;

Constants should be named after the hump method and prefixed with the associated class name.

// recommended
static const NSTimeInterval ZOCSignInViewControllerFadeOutAnimationDuration = 0.4; // Is not recommended
static const NSTimeInterval fadeOutTime = 0.4;

Constants are recommended instead of string literals and Numbers. It can be easily reused and modified quickly.

Constants should be declared as static constants using static, not #define, unless it is explicitly used as a macro.

// recommended
static NSString * const ZOCCacheControllerDidClearCacheNotification = @"ZOCCacheControllerDidClearCacheNotification"; static const CGFloat ZOCImageThumbnailHeight = 50.0f; // Is not recommended
#define CompanyName @"Apple Inc."
#define magicNumber 42

If the constant needs to be exposed externally, it should be in the header file as follows:

extern NSString *const ZOCCacheControllerDidClearCacheNotification;

And assign it a value in the implementation file.

Only public constants need to be prefixed with a namespace. Although the naming of private constants in the implementation file can follow another pattern, you can still follow this rule.

A space should be added between the method name and the method type (-/+ symbol).

Method segments should also be separated by Spaces.

The parameter should be preceded by a descriptive keyword.

Use the word "and" as sparingly as possible; it should not be used to clarify that there are multiple parameters.

// recommended
- (void)setExampleText:(NSString *)text image:(UIImage *)image;
- (void)sendAction:(SEL)aSelector to:(id)anObject forAllCells:(BOOL)flag;
- (id)viewWithTag:(NSInteger)tag;
- (instancetype)initWithWidth:(CGFloat)width height:(CGFloat)height; // Is not recommended
- (void)setT:(NSString *)text i:(UIImage *)image;
- (void)sendAction:(SEL)aSelector :(id)anObject :(BOOL)flag;
- (id)taggedView:(NSInteger)tag;
- (instancetype)initWithWidth:(CGFloat)width andHeight:(CGFloat)height;
- (instancetype)initWith:(int)width and:(int)height;  // Never do this.

Use literals to create immutable NSString,NSDictionary,NSArray, and NSNumber objects.

In this way, be careful not to put nil in NSArray and NSDictionary, which can cause crashes.

NSArray *names = @[@"Brian", @"Matt", @"Chris", @"Alex", @"Steve", @"Paul"];
NSDictionary *productManagers = @{@"iPhone" : @"Kate", @"iPad" : @"Kamal", @"Mobile Web" : @"Bill"};
NSNumber *shouldUseLiterals = @YES;
NSNumber *buildingZIPCode = @10018;


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];

Avoid creating mutable arrays in such a way:

// recommended
if ([myValue isEqual:@42]) { ... // Is not recommended
if ([@42 isEqual:myValue]) { ...
This approach has problems with both efficiency and readability.

Efficiency: an unnecessary immutable set is discarded immediately after it is created. It is not necessary.

Readability: readability is not good.

Related articles: