Summary of basic grammar of OBJECTIVE-C

Source: Internet
Author: User
Tags array sort

label:

1.NSLog (@ "hello world!"); // The function of printing statements, the string to be printed is placed after @.

NSLog (@ “are% d and% d different?% @”, 4,4, @ ”YES”);

2. The square brackets serve two purposes:

1) Accessing array elements

2) It is used to notify an object what to perform. The first item in square brackets is the object, and the rest is the operation that the object needs to perform. For example, [shape draw] means to inform shape to execute the draw method.

3. Method call: class name method name: parameter

Note: If the method uses parameters, a colon is required; otherwise, a colon is not required.

4. Class writing:

In the header file: @interface name

                … .// Declaration method

               @end

In implementation: @implementation name Note: There is no comma on this line

… .// Code implementation, the order may not be consistent with the order declared in the header file;

..... // In addition, you can also define methods that are not declared in the header file, you can treat them as private methods, and only use them in the class's ...

            @end

5.OC method implementation should pay attention to the sequence of calls:

  For example, method A needs to call method B, then method B needs to be implemented before method A.

 

6. Instantiate the object

 

7. C ++ has multiple inheritance features, but Objective-C does not support multiple inheritance. Inheritance refers to the relationship between two classes to avoid a lot of duplicate code.

 

8.OC inheritance knowledge:

When a subclass overrides a parent class method and calls this method, the implementation of the method in the parent class is completely ignored. In order to avoid ignoring the parent class method, the super keyword can be passed. At this time, the subclass's override method is still called The implementation method of the parent class is called.

 

9. Composition is achieved by including object pointers as strength variables. Strictly speaking, only combinations between objects are called composites.

[email protected] Creating a forward reference is telling the compiler: "Trust me, you will know what this class is in the future, but now you just need to know these".

@Class is also useful if you have circular dependencies. That is, type A uses type B, and type B also uses type A. If you try to reference these two classes with each other via the #import statement, you will end up with a compilation error. But if you use @class B in A.h and @class A in B.h, these two classes can reference each other.

 

11. The collection framework NSArray has two restrictions (NSArray is an array of immutable objects):

(1) Can only store Objective-C objects, not basic data types in C, such as int, float, struct, enum, etc. (2) Nil cannot be stored in NSArray.

** Create NSArray objects: arrayWithObjects: ..., ...., ..., .... nil; Send a comma-separated list of objects, add nil at the end of the list to indicate the end of the list. For example, NSArray * array;

array = [NSArray arrayWithObjects: @ “one”, @ “two”, @ “three”, nil];

** ObjectAtIndex method to get the specified index:

** Method to split a string into NSArray objects componentsSeparatedByString :();

 

12. Variable array NSMutableArray, you can add and delete elements at will, but the array itself is always the same.

** Create a variable array object NSMutableArray arrayWithCapacity: 3;

** Call-(void) addObject: (id) anObject; to add an object at the end of the array.

** Call-(void) removeObjectAtIndex: (unsigned) index; // Remove the object at the specified index. When the element at the relatively previous index is deleted, the following array elements are moved forward to fill the gap.

** You can also use NSEnumerator to traverse the array, the specific code is as follows:

        // Through the array through NSEnumerator

        NSEnumerator * enumerator;

        enumerator = [tArray objectEnumerator];

        id thingid;

        while (thingid = [enumerator nextObject]) {

            NSLog (@ "I found% @", thingid);

        }

 

** Quick enumeration:

        // Quick enumeration

        for (NSString * tmp in tArray) {

            NSLog (@ "I found% @", tmp);

        }

13. Collection framework NSDictionary: (121 pages)

Similar to map in Java, it uses the optimized storage method of key query, which is immutable object like NSString and NSArray.

 

14. NSArray and NSDictionary can only store objects, not basic type data, so the OC provides the NSNumber class to wrap basic type data (that is, implemented in the form of objects).

+ (NSNumber *) numberWithChar: (char) value;

+ (NSNumber *) numberWithInt: (int) value;

+ (NSNumber *) numberWithFloat: (float) value;

+ (NSNumber *) numberWithBool: (BOOL) value;

Generally, packing a basic type of data into an object is called boxing, and bringing out basic type data from an object is called unboxing. OC does not support autoboxing.

 

15.Array Sort by NSSortDescriptor Object

 

============ Memory management rules: If you use the new, alloc, or copy method to obtain an object, the object's retention counter value is 1, and it is responsible for releasing it ====== ====================================

 

16. Simplified interface

@property precompiled directives are used to automatically declare setter and getter methods for properties.

For example: In the past our pair of methods is as follows:

@interface car {

float engine;

}

-(void) setEngine; // Setting method

-(id) engine; // Get object method

@end

Now it can be implemented in a more characteristic way, as follows:

@interface car {

float engine;

}

@property float engine; // Replaces the setEngine and engine methods above, and is used in the header file

@end

17. Simplify implementation

@synthesize engine; // is a new compiler function, which means "create accessor for this property". When encountering the code @synthesize engine ;, the compiler will output the compiled code of the setEngine and engine methods.

 

The *** @ property feature only supports the methods mentioned above. It does not support methods that require additional parameters.

 

18. Read-only: @property special new is read-write by default, but features such as driver's license number or ID number, we do not want anyone to change it, we can use the read-only property of @property. E.g:

@property (readonly) float shoeSize;

The compiler will only generate a getter method for the property and not a setter method.

 

19. Categories are a way to add new methods to existing classes (such as class libraries, etc.). Categories also provide a way to distribute the implementation of an object across multiple different source files and even multiple different frameworks.

** The declaration format for categories is similar to the declaration format for classes:

@interface NSString (NumberConvenience)

-(NSNumber *) lengthAsNumber;

@end

The meaning of the above code is that the name of the category is NumberConvenience, and the category will add methods to the NSString class. That is, add a category named NumberConvenience to the NSString class. As long as the category names are guaranteed to be unique, you can add as many categories as you want to a class. Also, instance variables cannot be declared in a category.

** Category implementation

Implement your own method in @implementation section

@ implementation NSString (NumberConvenience)

-(NSNumber *) lengthAsNumber {

// Implement the code. . .

}

@end

Limitations of categories: 1. Cannot add new instance variables; 2. Name conflicts, that is, methods in a category have the same name as existing methods. When a name conflict occurs, the category takes precedence.

 

20. Delegate (don't understand), method selector

Categories allow you to declare informal agreements. Informal protocols are a category of NSObject, which can list the methods that objects can respond to. Informal protocols are used to implement delegation, which is a technique that allows you to easily customize the behavior of objects.

Selectors are a way to specify specific Objective-C messages in your code.

 

21. Formal agreement

*) The following is a statement of the agreement

@protocol NSCopying

-(id) copyWithZone: (NSZone *) zone;

@end

Note that when the protocol is declared, the protocol name must be unique. Each adopter of the protocol must implement these methods. The use protocol does not introduce new instance variables.

*) Adoption agreement

@interface Car: NSObject <NSCopying, NSCoding> {// Two protocols are used

// Instance variables

}

// method declaration

@end

Note ###: The name of the protocol is enclosed in angle brackets. When multiple protocols are used, they can be listed in any order without any impact on the order.

 

22. Copy (copy) is divided into shallow copy (shadow copy) and deep copy (deep copy).

Shallow copy: Reference objects are not copied, newly copied objects only want existing reference objects. The copy method of the NSArray class is a shallow copy. When copying an object of the NSArray class, you copy only the pointer to the reference object, not the reference object itself. If you copy an NSArray object that contains 5 NSString objects, you end up with 5 string objects that can be used by the program instead of 10 string objects.

 

Deep copy: All referenced objects will be copied. If the copy method of the NSArray class is a deep copy, you will get 10 available string objects after the copy operation is complete.

Objective-C basic syntax summary

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.