Objective-c syntax (3): objective-c syntax

Source: Internet
Author: User

Objective-c syntax (3): objective-c syntax

Anonymous objects in oc

Oc is rarely used here, because it is not suitable for the memory management of oc, but may appear in the interview test, which requires understanding. Do not write it like this in the project, because writing anonymous objects will cause memory leakage.

# Import <Foundation/Foundation. h> @ interface Car: NSObject {@ public int speed;}-(void) run; @ end @ implementation Car-(void) run {NSLog (@ "% d ", speed) ;}@ endint main () {// the so-called anonymous object is an object without a name and cannot be seen, but the object does exist in [Car new]-> speed = 300; // no pointer variable points to the object, but calls the member variable of the class directly, because every time you use [Car new], a new object will be created, so it is not 300, the default value is 0 [[Car new] run]; // 0 // Car * c = [Car new]; // c-> speed = 100; // [c run]; // 100 return 0 ;}

Just understand what it means.

Naming rules for class member variables
  • All member variables start with underscore _
  • The name can be separated from the get method.
  • It can be separated from other local variables. The variable starting with an underscore must be a member variable of the class.
Weak OC syntax

1. OC is a dynamic detection error. When OC calls an object method that is neither declared nor implemented, it will not generate an error but will warn that the link can pass. Only running can detect errors.

2. Only declarations but not implemented object methods are called in Oc. This compilation is also a warning. An error occurs only when the link is passed.

3. Oc calls only implement (not declared) methods, so there is no problem! Because the program is detected during running, the statement is actually just a decoration, and it is okay to delete it. But it is under development and must be standardized! You must write all the data. Even if no error is reported.

Class Method

Methods that can be directly executed using class names (Classes occupy storage space in the memory, including the class \ object method List)

1. Comparison between class methods and object Methods

1) object Method

  • Minus sign-start
  • This method can only be called by objects without objects.
  • Object methods can access instance variables (member variables)

2) Class Method

  • Starting with the plus sign +
  • It can only be called by class name, and the object cannot be called
  • Instance variables (member variables) cannot be accessed in class methods)
  • Usage scenarios: When you do not need to access member variables, use the class method whenever possible.

3) class methods and object methods can have the same name.

4) Improve Program Performance

Advantages and usage of class Methods: it does not depend on objects, and the execution efficiency is high. Class methods can be used, and class methods should be used whenever possible.

// All class methods start with + (void) printClassName;-(void) test; + (void) test; // class methods and object methods can have the same name

The self keyword indicates that the object is the receiver of the current method.

  • When the member variables and local variables have the same name, the proximity principle is adopted to access local variables.
  • Use self to access member variables and distinguish local variables with the same name

Details:

1) Where it appears: it can appear in all OC methods (Object Methods \ class methods), but it cannot appear in Functions

2) role:

Use "self-> member variable name" to access the member variables called by the current method

Use "[self method name];" to call a method (Object Method \ class method)

# Import <Foundation/Foundation. h> @ interface Person: NSObject {int _ age;}-(void) setAge :( int) age;-(void) test; @ end @ implementation Person-(void) setAge :( int) age {// _ age = age; equivalent to self-> _ age = age;}-(int) age {return self-> _ age;}-(void) test {// self: Directs to the caller, representing the current object int _ age = 20; NSLog (@ "Person's age is % d", self-> _ age) ;}@ endint main () {Person * p = [Person new]; [p setAge: 10]; [p test]; return 0;}/* self purpose: 1> who calls the current method, self indicates who * self appears in the object method, self indicates that the object * self appears in the class method, self indicates class 2. In the object method, use "self-> member variable name" to access the members of the current object. Change [self method name] to call other object Methods \ class Methods */ # import <Foundation/Foundation. h> @ interface Dog: NSObject-(void) bark;-(void) run; @ end @ implementation Dog-(void) bark {NSLog (@ "Wang ");} -(void) run {[self bark]; // self indicates the object pointed to by pointer d, NSLog (@ "Wang"); NSLog (@ "running ");} @ endint main () {Dog * d = [Dog new]; [d run]; return 0 ;}

Low-level error:

Use self to call Functions

Use self to call object methods, and use self to call class methods in object Methods

Self endless loop

# Import <Foundation/Foundation. h> @ interface Person: NSObject-(void) test; + (void) test;-(void) test1; + (void) test2;-(void) haha1; + (void) haha2; @ end @ implementation Person-(void) test {NSLog (@ "-test method called"); // If [self text] exists; this statement will lead to an endless loop. Because [self test]; self represents an object, the object method test} + (void) test {NSLog (@ "+ test method called") is always called "); // lead to an endless loop [self test]; self represents the class, always call the class method test} // automatic identification-(void) test1 {[self test]; // OK, -test} + (void) test2 {[self test]; // OK, + test}-(void) haha1 {NSLog (@ "haha1 -----");} // function void haha3 () {}+ (void) haha2 {haha3 (); // OK, be sure to note that functions and methods are different! // [Self haha3]; // error, cannot use self to call functions // [self haha1]; // error, in class methods, cannot use self to call object methods. On the contrary, in object methods, you cannot use self to call class methods} @ endint main () {[Person haha2]; // directly call the class method // Person * p = [Person new]; // [p test1]; return 0 ;}

 

In principle (if ARC is not used, that is, automatic reference count ),

To create a new object, you must request memory allocation. When you complete operations on the object, you must release the memory space used by the object.. Memory Management similar to c ++.

 

Compatible with C:

Preprocessing:

# The define statement is the same as that of c.

# Operator: # define str (x) # x

Indicates that when the macro is called, The Preprocessing Program creates a C-style constant string based on the macro parameters.

For example, str ("hello") will generate "\" hello "\"

# Operator: used to connect two tags

# Import Statement; equivalent to # include statement, but # import can automatically prevent the same file from being imported multiple times.

# The Conditional compilation statements (# ifdef, # endif, # else, # ifndef) are the same as those in C.

# The undef statement removes the definition of a specific name.


Other basic C language features:

Array, function, pointer, structure, Union usage is the same as C.

Compound Literal is the type name included in the brackets, followed by an initialization list.

For example

If intPtr is of the int * type:
IntPtr = (int [100]) {[0] = 1, [50] = 50, [99] = 99 };

If the array size is not specified, check the initialization list.

Others include loop statements (do while, while, for), condition statements (if-else, compound judgment conditions, etc.), switch statements), Boolean (yes no), conditional operators, goto statements, empty statements, comma expressions, sizeof operators, command line parameters, bit operations are the same as C.

Inheritance of oc

The inheritance of oc only supports a single inheritance, similar to java, that is, the son can only have one father,

Advantages of Multi-inheritance can be obtained through Objective-C classification and Protocol features

C ++ supports single and multi-inheritance.

Benefits:

Without changing the original model, the Extension Method

Establish a connection between classes

Extracted public code

Disadvantages:

Strong Coupling

Basically, the root class of all classes is the NSObject class.

The animal class has the new method of the NSObject class, And the subclass dog and cat both have all the methods and attributes of the first two classes. Similar to c ++ and java

# Import <Foundation/Foundation. h>/* 1. benefits of inheritance: 1> extracting repeated code 2> establishing the relationship between classes 3> subclass can have all member variables and methods in the parent class 2. note 1> basically, the root class of all classes is NSObject * // ********** Animal declaration *******/@ interface Animal: NSObject {int _ age; double _ weight;}-(void) setAge :( int) age;-(void) setWeight :( double) weight; -(double) weight; @ end/********* Animal implementation *******/@ implementation Animal-(void) setAge :( int) age {_ age = age;}-(int) age {return _ age;}-(void) setWeight :( double) weight {_ weight = weight;}-(double) weight {return _ weight;} @ end/********** Dog ******* // inherits Animal, it is equivalent to having all member variables and methods in Animal. // Animal is called the parent class of Dog, and Dog is called the subclass of Animal @ interface Dog: animal @ end @ implementation Dog @ end/********* Cat *******/@ interface Cat: animal @ end @ implementation Cat @ endint main () {Dog * d = [Dog new]; [d setAge: 10]; NSLog (@ "age = % d ", [d age]); return 0 ;}

Details in oc inheritance (similar to other object-oriented languages)

The parent class must be declared before the subclass.

The subclass and parent classes cannot have the same member variables, but the method can be rewritten.

Method rewriting problem: subclass re-implements a method in the parent class, that is, overwrite the parent method.

When a method is called, it is first found in the current class. If no method is found, it is found in the parent class.

This is an internal principle.

Each object has an isa pointer pointing to the class of the object. Remember: each class (oc) has a superclass pointer pointing to its parent class.

In this way, you can find the class that the object belongs to and the parent class of the class. These pointers are in the NSSobject class.

Memory Structure:

Inherited application scenarios

1> when two classes have the same attributes and methods, they can be extracted to a parent class.

2> when class A has partial attributes and methods in Class B, you can consider inheriting Class.

// Inheritance: xx is xxx

// Combination (also called aggregation): xxx owns xxx

Super keyword

After rewriting, you can also call the object methods and class methods of the parent class, the role of super; directly call a method in the parent class

1. If super is in the object method, the object method of the parent class will be called.

2. If super is in the class method, the class method of the parent class will be called.

Usage:

When a subclass overrides the parent class method, it wants to retain some behavior of the parent class.

In oc, it is much simpler to call a method. First, the method is located near the class where it is located, and the parent class cannot be found. It's too simple. If the parent class method is overwritten, you can only call this method that the subclass overrides. to retain the function defined by the original method of the parent class, you can use super.

Oc Polymorphism

Embodiment of Polymorphism

Person * p = [Student new];

P-> age = 100;

[P walk];

The subclass object is assigned to the parent class pointer. The parent class pointer accesses the inherited attributes and methods of the corresponding subclass.

Limitations of Polymorphism

You cannot access the unique attributes or methods of sub-classes (force conversion can be considered)

Polymorphism details

Dynamic binding: the dynamic calling method is determined based on the object type at runtime.

Note:

1. No polymorphism without inheritance

2. Code embodiment: the pointer of the parent class directs to the subclass object

3. Benefits: If the function \ method parameter uses the parent class type, you can pass in the parent class or subclass object

4. Limitations: variables of the parent class cannot directly call the method unique to the subclass. Only after being strongly converted to a subclass type variable can the unique method of the subclass be called directly (similar to the compatibility of c ++ assignment)

# Import <Foundation/Foundation. h> // Animal @ interface Animal: NSObject-(void) eat; @ end @ implementation Animal-(void) eat {NSLog (@ "Animal-eat ----");} @ end // Dog @ interface Dog: Animal-(void) run; // run @ end @ implementation Dog-(void), an object method added to the subclass) run {NSLog (@ "Dog --- run");}-(void) eat // override the-eat method of the parent class {NSLog (@ "Dog-eat ----") ;}@ end // Cat @ interface Cat: animal @ end @ implementation Cat-(void) eat // override the object method eat of the parent class {NSLog (@ "Cat-Taidong West ---- ") ;}@ end // If the parameter uses a parent class pointer, you can pass in the parent class or subclass object void feed (Animal *) {[a eat];} int main () {Animal * aa = [Dog new]; // The parent class Pointer Points to the subclass object // [aa run]; weak syntax, only warning! But in java or c ++, an error has long been reported! The parent class pointer cannot access the method unique to the subclass. Although the syntax is weak, it is not recommended, I think it is wrong. // it is OK to convert the parent class Object aa to the variable of the subclass Dog * type. It is similar to Dog * dd = (Dog *) aa in c ++; [dd run]; // OK. The object method of the subclass is run // Dog * d = [Dog new]; // [d run]; // OK/* Animal * aa = [Animal new]; pointer of parent class Object aa feed (aa); can be passed into parent class object as a parameter, call the eat method of the parent class Dog * dd = [Dog new]; subclass Object Pointer dd feed (dd); you can also input a subclass object as a parameter, call the eat method of the subclass Cat * cc = [Cat new]; feed (cc); call the subclass eat, and input the subclass object parameter * // polymorphism: the parent class Pointer Points to the subclass object Animal * a = [Dog new]; // The real image of the object will be detected when the method is called, dynamic [a eat]; the eat method of the subclass when calling */return 0 ;}

Limitations of polymorphism:

Variables of the parent class cannot directly call the method unique to the subclass.

Contact c ++

C ++ uses virtual functions (including pure virtual functions and abstract classes) to override virtual functions, parent class pointer, or reference to subclass, then you can call the override virtual function of the subclass to point to the parent class, that is, call the virtual function of the parent class to implement dynamic Association.

In oc, it is not so complicated. It means that the Child class inherits the parent class directly. To rewrite an object method of the parent class, the Child class pointer must point to the Child class object, and then the Child class override method is called, similarly, you cannot call methods specific to sub-classes.

It is concluded that the oc method is a virtual method! Do not use virtual declaration like c ++! In addition, oc rewriting is also a type of polymorphism. All method access attributes in oc are public! By default, class member variables are protected. Different from c ++, c ++ is private by default.

Let's look at the weak oc syntax! For example, point the subclass object pointer to the parent class.

Cat *cat = [Animal new];

C ++ is definitely wrong, but there is no problem in oc, only warning, but this is not good, not recommended. It's totally unreasonable.

Let's look at it again:

NSString *s = [Cat new];

Why does an animal become a String object? No error is reported for xcode in oc! But it is definitely not correct. It is not standard. In addition, for classes at the same level, the cat class Pointer Points to the dog Class Object and calls the eat method. In the weak oc syntax, it is still okay to call the dog's eat.

The oc is too weak! However, an error is reported directly in c ++. It cannot be written like this, even if the compiler does not report an error.

Benefits of Polymorphism

Using a parent class object to receive parameters, methods, or functions can accept subclass objects and parent class objects, saving code. Otherwise, separate multiple methods or functions.

Fully embodies the object-oriented abstraction and specifics. it overwrites the inherited Virtual Methods of the parent class through the subclass (which are all oc by default) and points the parent class pointer to the subclass object to achieve dynamic polymorphism! Instead of the pointer type, you can call the virtual method of the subclass object by looking at the object type pointed to by the pointer. Note that the method unique to the subclass is not acceptable and must be strongly converted.

 

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.