Objective-C basic core syntax-Summary, objective-c syntax

Source: Internet
Author: User
Tags call back

Objective-C basic core syntax-Summary, objective-c syntax

I. Grammar nature

  • "Point Syntax" is essentially "method call"
  • When the dot syntax is used, the compiler automatically expands the corresponding method.
1 // call method 2 Student * stu = [[Student alloc] init]; 3 [stu setAge: 10]; 4 int age = [stu age]; 5 // ------------------------------- I am a gorgeous split line ----------------------------- 6 // point syntax 7 stu. age = 10; 8 int age = stu. age;

II. Scope of member variables

  • @ Public: You can directly access the member variables of an object anywhere.
  • @ Private: It can only be accessed directly in the object method of the current class (@ implementation is @ private by default)
  • @ Protected: You can directly access the current class and the object method with tired words (default: @ protected)
  • @ Package: the member variables of the object can be directly accessed as long as they are in the same framework.
  • @ Interface and @ implementation cannot declare member variables with the same name
  • No @ interface. Only @ implementation can be used to develop the same class.

 

3. @ property and @ synthesize,SetterAndGetterAnd Usage Details

  • @ Property is used in @ interface to automatically generateSetterAndGetterOfStatement
  • @ Synthesize is always in @ implementation to generateSetterAndGetterOfImplementation
  • @ Synthesize details: 1> @ synthesize age = _ age ;(SetterAndGetterThe member Variable _ age is accessed during implementation. If the Member Variable _ age If it does not exist, an @ private member Variable _ age is automatically generated. )
    • 2> @ synthesize age ;(SetterAndGetterThe implementation accesses the member variable age. If the member variable age does not exist, an @ private member variable age is automatically generated)
    • 3> If you manually implementSetterMethod, the compiler will only automatically generateGetterMethod
  • Since Xcode4.4, @ property has exclusive features of @ synthesize. That is to say, @ property can be generated simultaneouslySetterAndGetterOfStatementAndImplementation.
  • By default, the setter and getter Methods access member variables starting with underscore _.
1 // -- [interface. h] --- Xcode4.2 syntax --------------- I am a gorgeous split line -------- 2 @ property int age; // @ property 3 // -- [interface. h] -------- values are equivalent to values -------- 4-(void) setAge; 5-(int) age; 6 7 // -- [implementation. m] ------------------------------- I am a gorgeous split line -------- 8 @ synthesize int age = _ age; // @ synthesize 9 // -- [implementation. m] --- values is equivalent to values -------- 10-(void) setAge {11 _ age = age; 12} 13-(int) age {14 return _ age; 15} 16 // -- [implementation. m] ------------------------------- I am a gorgeous split line -------- 17 @ synthesize int age; // @ synthesize18 // -- [implementation. m] --- response is equivalent to response -------- 19-(void) setAge {20 _ age = age; 21} 22-(int) age {23 return age; 24} 25 26 // -- [interface. h] --- Xcode4.4 with the following new syntax ------- I am a gorgeous split line ------- 27 @ property int age; // @ property28 // -- [interface. h] --------- percent is equivalent to %------- 29 @ interface Student: NSObject {30 int _ age; 31} 32-(void) setAge; 33-(int) age; 34 // -- [implementation. m] --------------------- 35-(void) setAge {36 _ age = age; 37} 38-(int) age {39 return _ age; 40}

 

Iv. id

  • Is a universal pointer that can point to any object, which is equivalent to NSObject *. Do not add * to the id *
  • The compiler will immediately report an error when calling a non-existent Method
  • Id is a struct, And the OC object itself is a struct.
1 typedef struct objc_object {2 Class isa; // each object has an isa, and isa always points to the current Class itself 3} * id; // id is defined as a structure pointer

 

5. Constructor (basic concepts, rewritingInitMethod,InitMethod execution process, custom)

  • Create a complete available object: 1> allocate storage space+ Alloc, 2> Initialization-Init(Steps 1> and 2> are continuously completed in the + new method)
  • Basic Concepts: The method used to initialize an object. It is an object method,-Starting,InitThe method is the constructor.
  • RewriteInitMethod: Must be called back to superInitMethod. Purpose: To create an object, the member variable has a fixed value.
  • 1 // ---- Student. m -------------
  • 2-(id) init {
  • 3 if (self = [super init]) // call back the init method of super and return the object self, that is, isa is the Student object.
  • 4 {// initialization successful
  • 5 _ age = 10;
  • 6}
  • 7 return self;
  • 8}
1 //------NSObject------------2 - (id)init {3     isa = [self class];4     return slef;5 }
  • InitMethod Execution Process: Initialize the parent class before initializing the Child class.
  • Custom: Specification: 1> it must be an object method.-Start with, 2> return value is generally id type, 3> method name is generallyInitStart
  • Good Habit of initialization: Initialize the member variables in the class implementation (advantage: decoupling. That is, when the parent class changes the member variable name, you do not need to change the code of the subclass)

 

6. Change the Xcode template (main. m, comment)

  • Main. m: For Mac Application Terminal Project: Enter/Users/jackieyi/Library/Developer/Xcode/Templates/Project Templates/Application/Command Line Tool. xctemplate/Templateinfo. plist: Modify the plist file as needed.
  • Note: For Mac Application Terminal Project: Enter/Users/JackieYip/Library/Deverloper/Xcode/Templates/File Templates/Cocoa/Objective-C class. xctemplate/NSObject/___ FILEBASENAME ___. m, or select the corresponding file as needed.

 

VII. Classification (basic usage, usage notes, adding class methods to NSString, and expanding object methods)

  • Function: You can add some methods to the class without changing the original class content.
  • Note:: 1> only methods can be added, but member variables cannot be added. However, in classification methods, the member variables of the original class can be accessed.
    • 2> classification can re-implement the methods in the original class, but will overwrite the original method, which will make the original method unusable.
    • 3> method call Priority: high | classification (the classification involved in compilation takes precedence)-> original class-> parent class | low
      • View the compilation sequence: Project-TARGETS-Builde Phases-Complie Sources, which is compiled from top to bottom (all files are. m files, and. h files are not compiled)

 

8. in-depth research on classes (nature, usage of class objects, loading and initialization of classes)

  • Nature: We know that each object has a type. The Class itself is also an object, referred to as "Class Object". The type of "Class Object" is Class type (Class contains *).
    • The object created by "Class Object" is called "Instance Object ".
    • By default, "Class Object" is loaded to the memory in only one copy. "Instance Object" can be loaded to the memory in multiple copies (different "instance objects ", its isa always points to the same "Class Object ").
1 Student * stu = [[Student alloc] init]; 2 Class stu1 = [stu class]; // create a Student Class Object using Class, [stu class] is used to obtain the Class object in the memory. 3 class stu2 = [Student class]; // the address of stu1 is equal to the address of stu2, which is the address of stu.
  • Use: "Class Object" can call "class method"
  • Load: It is a runtime mechanism. When the program starts, all classes and classes in the project will be loaded once (whether or not classes are used ). After the class is loaded, the + load method is called only once (first load the parent class, then load the subclass, and finally load the category)
1 + (void) load {2 // when the program is started, all classes call this loading method 3}
  • Initialization: It is a runtime mechanism. When the class is used for the first time, the + initialize method will be called (initialize the parent class first, and then initialize the subclass. If there is a category, only the category will be initialized)
1 + (void) initialize {2 // This method will be called once when class is used for the first time ([class alloc] init. Here we can monitor when the class is used 3}

 

IX. description Method

  • By default, when NSLog and % @ are used to output class objects, the result is: <Class Name: memory address>
  • Each time NSLog (@ "% @", "Instance Object") is called, The-description method of "Instance Object" is called by default, -the return value of the description method is (NSString *). By default, "class name + Memory Address" is returned"
  • You can override the-description method to output all member variables.
1-(NSSting *) description {2 // NSLog (@ "% @", self); // This line of code will lead to an endless loop 3 return [NSString stringWithFormat: @ "age = % d, name = % @", _ age, _ name]; 4}
  • Each time NSLog (@ "% @", "Class Object") is called, The + description method of "Class Object" is called by default, + The Return Value of the description method is (NSString *), and the "Class Name" is returned by default"
  • + Description can also be rewritten.

 

10. Supplement NSLog output

1 int main () {2 NSLog (@ "% d" ,__ LINE _); // output the current row number (that is, 2) 3 // NSLog (@ "% s" ,__ FILE _); // when NSLog outputs a C-language string, chinese 4 printf (@ "% s \ n" ,__ FILE _); // output source FILE name (including path) 5 NSLog (@ "% s \ n" ,__ func _); // output the current function name (that is, main) 6}

 

11. SEL (basic usage and other usage)

  • It is a runtime mechanism. A SEL represents a method, corresponding to the method address
  • When an object calls a method: 1> first, package the method into SEL-type data; 2> Find the corresponding method address based on SEL data; 3> call the corresponding method based on the method address.
1 int main () {2 Student * stu = [[Student alloc] init]; 3 [stu test]; 4 [stu primary mselector: @ selector (test)]; // call the test method indirectly. @ selector (test) is a SEL type 5 [stu receiver mselector: @ selector (test1 :) withObject: @ "123"]; // call test indirectly: method, @ selector (test :) is a SEL type 6}
1 NSString * name = @ "test"; 2 SEL s = NSSelectorFromSrting (name) // package the test method into SEL data 3 [stu executor mselector: s];
  • Each method contains _ cmd of SEL data, and _ cmd represents the current method. When a message is sent to an object, SEL data is transmitted to the object. SEL cannot be printed directly, but can only be converted into strings for printing.
1-(void) test {2 NSString * str = NSStingWithSelector (_ cmd); 3 NSLog (@ "the test method is called --- % @", str); // display: the test method --- test4} is called}

 

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.