Objective-C: 06 _ object-oriented-core syntax

Source: Internet
Author: User
Point Syntax:    The essence of point syntax is method call.When the dot syntax is used, the compiler automatically expands to the corresponding method person * P = [person new]; P. Age = 10; // The Compiler automatically converts this line of code to [p setage: 10] during compilation; Int A = P. Age; // The Compiler automatically converts this line of code to int A = [P age] during compilation.Do not create an infinite loop when using the dot Syntax:-(void) setage :( INT) Age
{
// The following code will lead to an endless loop, which is equivalent to [self setage: Age]
Self. Age = age;
}
-(INT) Age
{
// The following code will lead to an endless loop, which is equivalent to [self age]
Return self. Age;
}
  Four Scopes of member variables: @ PRIVATE: It can only be accessed directly in the object method of the current class (@ implementation is not written. The default value is @ private) @ Protected: You can directly access the object method of the current class and its subclass (@ protected is the default value in @ interface) @ Public: Access member variables of an object anywhere@ Package: the member variables of the object can be directly accessed as long as they are in the same framework, between @ private and @ public. When nothing is written, the default access level is protected.Member variables can also be written in the implementation section, that is, in the. M file, The default access level is @ private.The member variables declared in the. M file cannot be the same as the member variables declared in the. h file (that is, the @ implementation and @ interface files) Only single inheritance is allowed in oCParent class \ superclass subclass \ subclasses @ Property and @ synthesizeThese two keywords are compiler features @ Property: the set and get methods of a member variable can be automatically generated.Member variables: int _ age; int _ height; nsstring * _ name; Declaration of get and set methods: @ Property int age; it is equivalent to the following two statement codes:-(Void) setage :( INT) age;-(INT) age; @ Property nsstring * Name;When multiple member variables have the same type, you can use @ Property type member 1, member 2, member 3;Implementation of get and set methods: @ Synthesize age = _ age; // equivalent to the following two methods (@ synthesize automatically generates the set and get methods of age and accesses the member Variable _ age) If it is @ synthesize age; // by default, the access is not the member Variable _ age, but the member variable Age.  -(Void) setage :( INT) Age {_ age = age;}-(INT) Age {return _ age;} if no member variable is written, but @ property is written, if @ synthesize is used in @ implementation, access the member variable. If it does not exist, the @ private member variable is automatically generated. The data type is based on the data type in @ property. (This variable is generated in @ implementation)   The simplest method: Directly write a @ property int age; The task that will be completed: 1. Generate get and Set Methods Declaration for age 2. generate an int type member variable int _ age. (because the generated variable is @ private, if the subclass needs to be accessed, we still need to write the member variable by ourselves, in this way, no private member variables will be generated) 3. Get and set methods of age generation  @ Synthesize details@ Synthesize age = _ age 1. In the setter and getter implementations, the member Variable _ age is accessed. 2. If the member variable does not exist, an @ private member Variable _ age @ synthesize age 1 will be automatically generated. The setter and getter variables will be accessed in implementation 2. If the member variable age does not exist, the @ private member variable Age is automatically generated for manual implementation. 1. If the setter method is manually implemented, the compiler will only generate the getter method automatically. 2. If the getter method is manually implemented, the compiler will only automatically generate the setter method 3. If the setter and getter methods are implemented manually at the same time, the compiler will not automatically generate nonexistent member variables IDID is a universal pointer that can point to \ to operate any OC object Id contains *, so no need to include * When declaring a variable *Nsstring * (string) is also an OC object, so the ID can also point to a string That is to say, ID is equivalent to nsobject *ID type definition: typedef struct objc object {class ISA;} * ID; Limitation: when calling a method that does not exist, the compiler will immediately report an error Constructor: Object MethodConstructor: A method used to initialize an object. It is an object method. The constructor starts with "-". Objective: To create an object, the member variable has some fixed values: person * P = [person new]; Create an object using the new method (two methods are called respectively to complete the following work ): 1. Allocate storage space (+ alloc) 2. Initialization (-init)Work performed inside the new method: // call + alloc method to allocate the bucket person * P1 = [person alloc]; // call the-init method to initialize person * P2 = [P1 init]; The init method is the constructor: equivalent to: person * P = [[person alloc] init]; after the object is initialized, the default member variable of the object is 0. when each person object is required to be created, its member Variable _ age is 10. Note: 1. First call the constructor of the parent class ([Super init]) 2. initialize the member variables in the subclass. // Rewrite-init Method
-(ID) Init { // 1. You must call the super init method to initialize some member variables and other attributes declared in the parent class.   // 2. if the object is initialized successfully, it is necessary to perform subsequent initialization. If ( Self = [Super init] ) { // Initialization successful _ Age = 10; } // 3. Return an object that has been initialized Return self; }
  Custom constructor:The above init method can only be rewritten internally to assign initial values to member variables. declared objects are the same as custom constructors in two steps: Step 1: declare Step 2: Implement Custom constructor specifications: 1. It must be an object method and must start -. 2. the return value is generally ID type. 3. method names generally start with initwithDeclaration:-(ID) initwithname :( nsstring *) Name; implementation:-(ID) initwithname :( nsstring *) name {If (Self = [Super init]) {_ name = Name;} return self;} when the initialization method in the subclass needs to use the member variables of the parent class, the principle is: the member variables in the subclass are initialized in the subclass, the member variables of the parent class are initialized in the parent class. (The initialization method is provided in the parent class, and then the subclass passes the value) the advantage is that when the member variables in the parent class change, no error will be returned if the subclass does not need to be changed. Just change the parent class. Category: Category Category: You can expand some methods for a class (without modifying the code of the original class)-"equivalent to partial in C # // Statement @ Interface Class Name (category name)   @ End // Implementation @ Implementaion Class Name (category name)   @ End  Note: 1. Only methods can be added for classification, but member variables cannot be added. 2. You can access the member variables declared in the original class in the classification method implementation. 3. If the method in the category has the same name as the method in the original class, the method in the category is preferentially called. (This will overwrite the methods in the original class, and the methods in the original class will not be used) 4. method call priority: Classification (the classification involved in compilation takes precedence) --> original class --> parent class Characteratindex: <# (Nsuinteger) #>: This method is used to obtain characters at a specified position (the position number starts from 0) Class nature:1. A class is also an object. Abbreviation "Class Object"-> Actually, a class is an object of the class type. The class keyword contains *, which is not followed *Create a person object using the person object // Obtain the class object in the memory (the obtained class object can call the class method) Person * P = [[person alloc] init]; Class C = [P class]; Or: Class C = [person class];Class loading process: + (Void) load: method called when the class is loaded When the program starts, it loads all classes and calls the + load method of all classes and classes. Load the parent class first, then load the subclass, that is, call the + load of the parent class first, and then call the + load of the subclass. First load the original class, then load the category No matter whether this class is used during the program running, it will call + load Load   + Initialize When you use a class for the first time (such as creating an object), The + initialize method will be called once. A class only calls the + initialize method once. First, the parent class is called. When the program starts, all classes and categories in the project will be loaded. After the program is loaded, the + load method for each class and category will be called. The load method of the original class will be called first, call the load method of classification later When a class is used for the first time, the + initialize method of the current class is called. First load the parent class and then load the subclass (first call the + load method of the parent class, and then call the + load method of the subclass) Initialize the parent class first, and then initialize the Child class (first call the + initialize method of the parent class, and then call the + initialize method of the Child class) Description method: -Description (determines the output result of the Instance Object)  Person * P = [[person alloc] init]; // by default, when an object is output using nslog and % @, the result is: <Class Name: memory Address> nslog (@ "% @", P ); The placeholder used to print the OC object is % @When printing the OC object (except nsstring *), the class name and the address of the class in the memory are displayed, and nslog (@ "% @", P) is executed: 1. First, the-description method of object P is called. 2. The returned value of the-description method (nsstring *) is displayed on the screen. 3. By default, the "Class Name: memory Address "when you want to output the object content, you can overwrite the-description method in the class implementation:-(nsstring *) Description
{Return [nsstring stringwithformat: @ "age = % d, name = % @", _ age, _ name];}
Do not output self: nslog (@ "% @", self) in description. This will lead to an endless loop. + Description (determines the output result of the Class Object)Class C = [person class]; // The + description method of the class will be called // The returned value of the + description method (nsstring *) will be displayed on the screen (the class name is returned by default) nslog (@ "% @", C ); Nslog (): Print the memory address of the object stored in the pointer: Nslog (@ "% P", P ); Print the memory address of the pointer variable: Nslog (@ "% P", & P ); When nslog () Outputs a c string, it cannot contain Chinese characters.Nslog (@ "% s", _ FUNC _); // output the name of the current method nslog (@ "% d", _ line _); // output the current line number nslog (@ "% s", _ file _); // output the complete path nslog (@ "% s" ,__ pretty_function _) of the current source file __); // return the complete function name (including the return value and parameters) of the current method or function)   Sel typeIs a type. A class contains sel data. A sel data corresponds to the address of the method person * P = [[person alloc] init]; [p Test2]; 1. Wrap Test2 into sel-type data 2. Find the corresponding method address based on sel data 3. Call the corresponding method based on the method address (the cache technology used here will be searched for the first time, the first search result will be used later) Indirectly call the Test2 Method [P performselector: @ selector (Test2)];Method storage location: The method list of each class is stored in the class object. Each method has a sel-type data corresponding to it. The method address can be found based on a sel object, then call the definition typedef struct objc_selector * sel of SEL type; SEL object creation sel S = @ Selector (test );Sel S2 = Nsselectorformstring (@ "test "); Nsselectorformstring (@ "test "); // Transfers data of the string type to the SEL data Each method has a sel-type data _ cmd, pointing to the current method.[Self defined mselector: _ cmd] cannot be used in the method. SEL is actually a method packaging. It encapsulates the method into a sel type data and finds the corresponding method address, find the method address to call the method. Actually, the message is Sel.

Objective-C: 06 _ object-oriented-core syntax

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.