Objective-C code Quality Improvement objective 1: Simplified writing and Objective-c Machine

Source: Internet
Author: User

Objective-C code Quality Improvement objective 1: Simplified writing and Objective-c Machine


Caution for improving OC code quality 1. OC features

  • OC has added the object-oriented feature for the C language, which is its superset;
  • OC uses a dynamically bound message structure, that is, the object type is checked during runtime;
  • The code to be executed after receiving a message is determined by the runtime environment, rather than the compiler;
    Ps: Understanding the core concepts of C language helps write the OC program, especially the memory model and pointer.
Ii. Introduce as few header files as possible in Class header files
  • Do not introduce header files unless necessary. Generally, it should be used in the header file of a class.Forward Declaration@class MEPerson;And introduce the Class header files in the implementation file. This can minimize the numberCoupling(Couping );
  • Sometimes unavailableForward Declaration(@class MEPerson;)For example, declare that a class complies with the intent protocol. In this case, try to move the statement "this class complies with a certain agreement" to "Category. If not, put the Protocol in a separate header file and introduce it.
3. Use the literal syntax (abbreviated syntax)
  • Fan:NSNumber *num = [NSNumber numberWithInt:1];
  • Simple:NSNumber *num1 = @1;
  • Benefit: this syntax can be used for all data types that can be expressed by the NSNumber strength.
    NSNumber *intNum = @1;NSNumber *floatNum = @2.5f;NSNumber *doubleNum = @3.14159;NSNumber *boolNum = @YES;NSNumber *charNum = @'a’;
    Simpler Syntax:
    int x = 5;   float y = 6.32f;   NSNumber *expressionNum = @(x * y);
    1> Array
  • Fan:
    NSArray * animals = [NSArray arrayWithObjects: @ "cat", @ "dog", @ "mouse", @ "badger", nil]; // (in this way, if the value is nil, an exception is thrown)
  • Simple:NSArray *animals1 = @[@"cat", @"dog",@"mouse",@"badger"];
  • Fan:NSString *dog = [animals objectAtIndex:1];
  • Simple:NSString *dog1 = animals[1];

Thrown exception: insert nil object from objects [0] (if the value is nil)
Cause: arrayWithObjects: The method processes parameters in sequence until nil is found;
From this perspective, the short form is safer.

2> dictionary
Instance

  • Fan:
    NSDictionary *personData = [NSDictionary dictionaryWithObjectsAndKeys: @"rose",@"fistName",@"may",@"lastName", [NSNumber numberWithInt:28],@"age", nil];
  • Simple:
    NSDictionary *personData1 = @{@"rose": @"fistName",@"may" : @"lastName", @"age" : @28 };
    Value
  • Fan:
    NSString *lastName = [personData objectForKey:@"lastName"];
  • Simple:
    NSString *lastName1 = personData1[@"lastName”];

Variable array and Dictionary

  • Fan:
    [NSMutableArray replaceObjectAtIndex:1 withObject:@"dog"];
  • Simple:

    NSMutableArray[1] = @"dog";
  • Fan:

    [NSMutableDictionary setObject:@"rose" forKey:@"lastName"];
  • Simple:
    NSMutableDictionary[@"lastName"] = @"rose”;
    Small limitation: Except for strings, the created objects must belong to the Foundation framework. If you customize these subclasses, you cannot use the literal syntax to create their objects.
    The preceding steps are immutable. If you want to change the parameters, You need to copy one copy.
    NSMutableArray *mutable = [@[@1, @2, @3, @4, @5]mutableCopy];

Key points:

  • You should use the literal syntax to create strings, numbers, arrays, and dictionaries. This is more concise than the conventional method for creating such objects;
  • The element corresponding to the array subscript or dictionary key should be accessed through the subscript operation;
  • When an array or a free point is created using the literal syntax, If nil exists in the value, an exception is thrown. Therefore, make sure that the value does not contain nil.
4. Multi-purpose type constants and less use # define preprocessing commands

Use less:#define ANIMATION_DURATION 0.3
Best use:

// Variables must be declared using both static and const. Only in. m usage // MEView. h // MEView. mstatic const NSTimeInterval MEAnimationDuration1 = 0.3; // Example 1: // MEView. hextern const NSTimeInterval MEAnimationDuration; // MEView. mconst NSTimeInterval MEAnimationDuration = 0.3; Example 2: // MEView. hextern NSString * const MEStringConstant; // MEView. mNSString * const MEStringConstant = @ "VALUE ";

Key points:

  • Do not use preprocessing commands to define constants. The defined constants do not contain type information. The Compiler only performs the search and replacement operations before compilation. Even if a constant value is redefined, the compiler will not generate warning information, which will lead to inconsistent constant values in the application;
  • Use static const in the implementation file to define "translation-unit-specific constant )". because such constants are not in the global constant table, you do not need to add a prefix for their names;
  • Use extern in the header file to declare global constants and define their values in the relevant city and county files. Such constants must appear in the global symbol table, so their names should be separated. They are usually prefixed with their related class names.
5. Use enumeration to indicate the status, options, and status code.

Because OC is based on the C language, it has all the functions of C language.
Enumeration is just a constant naming method.

The various states of an object can be defined as a simple enumeration set.
For example:socket connection

  • First case: Use the serial number assigned by the System

    enum MEConnetionState {MEConnetionStateDisconnected,MEConnetionStateConnecting,MEConnetionStateConnected,}

    Because each State is represented by a value that is easy to understand, the code written in this way is easier to understand. The compiler will assign a unique number to the enumeration, starting from 0, with each enumeration increasing by 1.

  • Case 2: You can manually specify the value of an enumerated member variable instead of the serial number assigned by the compiler.

    enum MEConnetionState {MEConnetionStateDisconnected = 1,MEConnetionStateConnecting,MEConnetionStateConnected,}
  • The third case is when the enumeration type is used, that is, when the option is defined. If these options can be combined, this should be more true
    enum UIViewAutoresizing {  UIViewAutoresizingNone                 = 0,  UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,  UIViewAutoresizingFlexibleWidth        = 1 << 1,  UIViewAutoresizingFlexibleRightMargin  = 1 << 2,  UIViewAutoresizingFlexibleTopMargin    = 1 << 3,  UIViewAutoresizingFlexibleHeight       = 1 << 4,  UIViewAutoresizingFlexibleBottomMargin = 1 << 5,}

As long as the enumeration is defined correctly, the options can be combined by "bitwise OR operator.
You can use the preceding method to define the enumerated values. Each option can be enabled or disabled.
This method is frequently used in the system library.

- (NSUInteger)supportedInterfaceOrientations {    return UIInterfaceOrientationMaskPortrait |            UIInterfaceOrientationLandscapeLeft;}

System syntax (new syntax ):

typedef NS_OPTIONS(NSUInteger, UIViewAutoresizing) {    UIViewAutoresizingNone                 = 0,    UIViewAutoresizingFlexibleLeftMargin   = 1 << 0,    UIViewAutoresizingFlexibleWidth        = 1 << 1,    UIViewAutoresizingFlexibleRightMargin  = 1 << 2,    UIViewAutoresizingFlexibleTopMargin    = 1 << 3,    UIViewAutoresizingFlexibleHeight       = 1 << 4,    UIViewAutoresizingFlexibleBottomMargin = 1 << 5};

New features are supported, defined using NS_ENUM:

typedef enum : NSUInteger { MEConnetionStateDisconnected, MEConnetionStateConnecting, MEConnetionStateConnected, } MEConnetionState;

Usage of enumeration in the switch statement:
All enumerations that need to be combined by bit or operation should be defined using NS_OPTIONS. If enumerations do not need to be combined, NS_ENUM should be used to define

typedef NS_ENUM(NSInteger, MEConnetionState) { MEConnetionStateDisconnected, MEConnetionStateConnecting, MEConnetionStateConnected,};
switch (_currentState) {        MEConnetionStateDisconnected:            break;        MEConnetionStateConnecting:            break;        MEConnetionStateConnected:            break; }

Note: If you use enumeration to define the state machine, it is best not to have a default branch.

Key points:

  • Enumeration should be used to indicate the state of the state machine, the options passed to the method, and the State Code Equivalent, giving these values an easy-to-understand name.

  • If the option passing a method is represented as the enumeration type, and multiple options can be used at the same time, the options are defined as the power of 2, in order to combine them by bit or operation.

  • Use the NS_ENUM and NS_OPTIONS macros to define enumeration types and specify their underlying data types. This ensures that enumeration uses the underlying data type selected by the developer to come true, rather than the type selected by the compiler.

  • Do not default the branch in advance in switch statements that process enumeration types. In this case, the compiler will prompt the developer that the swith statement does not process all enumerations after the new beauty drama is added.

Summary

Only by gaining an in-depth understanding of the characteristics of the OC language, clarifying the habits of writing code on weekdays, which writing methods can improve efficiency, and strictly require yourself to ensure high-quality code production. The five points mentioned above are frequently used on weekdays. These small code specifications play a leading role in improving the quality of your entire program code. Of course, this is also the basis for high-quality code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.