(Reproduced) OC syntax Summary

Source: Internet
Author: User

1. Definition class:
@ Interface Class Name: parent class
@ End

2. Use: (colon) to inherit a class
Student: nsobject

3. Use () to define a catagory (category)

* Function: extend the methods of the original class (attributes cannot be extended) without changing the structure of the original class. However, it is not recommended to reload the methods of the original class.

* The default file generated by the development tool is: class name + catagory name
* Catagory can be written in a separate file or in an original class file. You can decide how to write catagory based on your needs.


4. Use <> to implement a protocol. To implement multiple protocols, separate the Protocol names with commas (,) in brackets.

* It can be understood as an interface in Java, but the difference is that the implementation class compiler does not forcibly implement all interfaces defined in protocol.
* Mark the method Signature: @ required. Literally, the implementation class must implement this method. In fact, the write effect is the same as that of the non-write method. It is also the default
* Mark the method Signature: @ optional, which indicates that the implementation class implements the method and is optional.


5. Attribute Access Permissions

* Private: only the class can be accessed internally.
* Protected: the class can be accessed internally and subclass (default)
* Public: no access restriction

Example:

// Define

@ Interface Student: nsobject {

@ Private int _ age;
@ Protected int _ No;
@ Public float _ height;

}
@ End

// Use
Student * Stu = [[STUDENT alloc] init] autorelease];
Stu-> _ Height = 20; // The value of the direct read/write attribute. This is generally not recommended during development. Violating the object-oriented development principles-encapsulation

6. Attribute definition and Encapsulation
// In student. h
@ Interface Student: nsobject {

// 1. Define attributes. The default access permission is @ protected, which can be directly accessed only by the user and subclass.
Int _ age; // we recommend that you underline the attribute name in the OC syntax to distinguish it from the parameter name.
Int _ No;

}

// 2. Provide the declaration of the attribute read/write Method for external calls. The naming rule for the read/write method for creating properties in OC is: Set Method: Set + attribute name, get method: attribute name
// Declare the get and set methods of age
-(INT) age;
-(Void) setage :( INT) age;

// Declare the no get and set methods
-(INT) No;
-(Void) setno :( INT) No;
@ End

// In student. m implements the method in the header file
# Import "student. H" // import the header file
@ Implementation student

// Implement the methods in the header file
-(INT) Age {// age's getter Method

Return _ age;

}

-(Void) setage :( INT) Age {// age setter Method

_ Age = age;

}

-(INT) No {

Return _ No;

}

-(Void) setno :( INT) No {

_ No = no;

}
@ End

7. Use @ synthesize to automatically generate the implementation of the getter and setter attributes, and generate a member variable with an underscore (_) + attribute name. It must be used with @ property. Example:
@ Implementation student

@ Synthesize age; // The get and set methods at the top of the sentence, automatically generated by @ synthesize
/*
* 1. If the get method is implemented, @ synthesize will automatically generate the Set Method of the attribute.
* 2. If the set method is implemented, @ synthesize will automatically generate the get method of the attribute.
* 3. If neither the get method nor the set method is implemented, @ synthesize will automatically generate the get and set methods of the attribute.
*/
-(INT) Age {// age's getter Method

Return _ age;

}

-(Void) setage :( INT) Age {// age setter Method

_ Age = age;

}

@ End

Note: In the compilation environment after xcode4.5, you do not need to write @ synthesize to declare the get and set methods for generating attributes. You only need to define @ property in the header file to automatically generate the get and set methods for the corresponding properties in the. M file.

 

8. Use @ property to declare an attribute. the compiler will automatically generate the getter and setter methods for this attribute.

In a compiler environment later than xcode4.5. the standard implementation of the getter and setter methods of this property is generated in the M file, and the @ synthesize is not required to display the Declaration to generate the getter and setter methods of the property.


9. @ Property Parameters
1> nonatomic: In a multi-threaded environment, no thread protection is required (no lock is required during read/write operations ),
Atomic: (default) thread protection is required in multi-threaded environments (locking during read/write ).
2> readonly: indicates that only the getter method of the attribute is generated in the. M file.
Readwriter: indicates the implementation of the getter and setter methods for generating attributes in the. M file (default)
3> retain: When the setter method of this attribute is called, the old value of release is first followed by the new value of retain. This parameter is added only when the declared member variable is a subclass of nsobject.
Assign: generate standard getter and setter methods (default) and assign values directly to attributes.
4> getter =: the name of the getter method generated by the custom property.
Setter =: the name of the setter method generated by the custom property.

10. method call
* [Instance Object method name: parameter list]
* [Class name Method Name: parameter list]
Example:
Student * Stu = [[STUDENT alloc] init] autorelease];
[STU setage: 22 andno: 10]; // call the instance method

[STUDENT initwithage: 20]; // call a static method

11. Point (.) syntax
Student * Stu = [[STUDENT alloc] init] autorelease];
Stu. Age = 20; // It is equivalent to calling the setage method of the object (write)
Int age = Stu. Age; // It is equivalent to calling the object's getage method (read)

12. Self keyword
This is equivalent to this in Java. The difference is that self works differently in different environments. In the instance method, self can be used as this object, and in the static method, self can be used as a class object.
For example:
-(Void) Age {
Return self. Age; // here, self is the instance object itself
}

+ (ID) newinstace {

// Student * Stu = [[STUDENT alloc] init] autorelease];
Student * Stu = [[self alloc] init] autorelease]; // This sentence is equivalent to the effect of the previous code, the Java syntax does not allow this to appear in static methods.

Return Stu;
}

13. @ Class: declare the existence of a class in the header file

To improve efficiency, you do not need to import the header file of a class if you only need to know the existence of the class.

// # Import "book. H"
@ Class book; // you do not need to import the book. h header file. Import the file again when the. M file is actually used.
@ Interface Student: nsobject
@ Property Book * book;
@ End

14. @ Protocol: declare the existence of a protocol in the header file

Same as @ Class


15. ^: defines a block type, which is very similar to the writing method for pointing to the function pointer type in the Standard C syntax.
For example, define the block type of a sum. The returned value is int, which has two int parameters.
INT (^ sum) (INT, INT) = ^ (int A, int B ){

Return A + B;

};

16,# Import: the header file used to import a class
# Pragma MARK: Comment on the write Method
# Pragma mark-: Method comment Group
+: Declare or define a static method
-: Declare or define an instance method

17. method definition(A colon represents a parameter, and a colon is also a part of the attribute method)
Method Type (Return Value Type) method name [parameter list] {(a colon represents a parameter, and a colon is also a part of the attribute method)
// Method body
}

* Instance method, Method Name: sumage: andno:
-(INT) setage :( INT) age andno :( INT) No {
// Insert the code logic here
}

* Static Method
+ (ID) initwithage :( INT) Age {
// Insert the code logic here
}
Note:
* The instance method is accessed through the Instance Object of the class.
* Static methods are accessed by class name or self

18. Memory Management
1> all classes inherited from nsobject need to manage the memory by themselves. In the OC syntax, any object created has a reference counter, the reference counter is 1 when it is created for the first time. When the reference counter value is 0, the object will be destroyed. Memory management involves the following interfaces:
* Release: The reference counter of the object minus 1.
* Retain: Add 1 to the Reference Counter of the object
* Retaincount: obtains the number of counters currently referenced by an object.

Object lifecycle callback interface:
* Init: the default constructor of an object. If a custom constructor is used to initialize a member variable, you must first call the constructor of the parent class and determine whether the obtained object is nil, then initialize the member variable.
For example:-(void) initwithage :( INT) Age {

If (Self = [Super init]) {
_ Age = age;
}
Return self;

}

* Dealloc: when an object is destroyed, the system automatically calls this method. This method usually releases memory or other resources. When rewriting the dealloc method, pay attention to calling the dealloc method of the parent class at the end of the Code to release memory and other related resources.

For example:

-(Void) dealloc {

[_ Book release]; // release member variables
[Super dealloc];

}
 
2> objects that do not need to manage memory
* Basic Data Type
* The built-in class of the system calls its own static method to create the object. It Automatically releases the memory and does not need to be managed.

3> memory management principles
Only when alloc, retain, copy, and new messages are sent to the object can the release operation be necessary.
* Who alloc, retain, copy, new who release
* Who creates and releases (Release)
* If there is no allock, retain, copy, or new, do not perform the release operation.

4> Automatic Memory Management (managed by autoreleasepool)
When you create an object, call the autorelease method to automatically store a reference to the recently created Auto Release release pool. In the future, you do not need to manually perform the release operation for this object. Xu Fei performed retain, copy, and other operations to modify the reference counter. When the automatic release pool is destroyed, a release message is sent to all objects in the pool. The reference counter of all objects in the pool is reduced by 1, this object will be completely destroyed only when the reference counter in the pool is 0. It does not mean that as long as the object is handed over to the automatic release pool, the pool is destroyed, and all objects in the pool will be destroyed.

For example: @ autoreleasepool {

Student * Stu = [[STUDENT alloc] init] autorelease]; // The Stu object will be placed in this braces to automatically release the pool.

[STU retain]; // if this sentence is added, the Reference Counter of Stu is 2 at this time. If no release message is sent to the object before the pool is destroyed, even if the pool is destroyed, this object will still cause memory leakage.

} // When the program is executed here, the automatic release pool is destroyed, meaning that all objects in the pool will receive a release message.

19. Java-like tostring method in oC
Student * Stu = [[STUDENT alloc] init] autorelease];
Nslog (@ "% @", Stu); // The memory address of the stu object is printed by default.

* Override the description method of the parent class to customize the information of the printed object.
-(Nsstring *) Description {
Nslog (@ "Age is % I", _ age );

}

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.