Keyword explanation commonly used in IOS

Source: Internet
Author: User

  1. # Synthesize Keyword: automatically generates an access method for the member variable according to the @ Property setting, so that the point operator can be used to conveniently access the member variable.

  2. @ Implementation indicates the implementation of the class @ end

  3. Self Keyword: similar to this in Java, It is a hidden parameter that points to the class of the currently called method.

Super Keyword: Call the method of the parent class.

Self = [superinit] This is not to judge whether self and [superinit] are equal, but whether the initialization is successful. [Super init]: If the parent class is initialized successfully, pass = to self, so that self becomes a non-empty object, which is not false (non-no ).

# Import tells the Preprocessor to include the header file content in this file. The import in the. OC ensures that the header file will only be contained once. @ interface Keyword: declare a student class. @ End
End statement.

 

Colon: indicates that the parent class is inherited.

Nsobject is the memory management used by most objects. It is equivalent to the initialization framework, reflection, and type operations.

NS is short for nextstep, indicating that this function comes from the cocoa toolkit.

  1. Declare global variables, as in C.

  2. Property keywords: Set the attributes of member variables (including read/write, assign, retain, copy, and nonatomic support for multithreading ).

  3. Declare a method in the format of-(Return Value) method keyword 1: (parameter type) parameter name method keyword 2: (parameter type) parameter name ...... (When reading a method, you can first find the method keyword to determine the parameter ).

-The minus sign is the instance method, and the plus sign is the class method.

4. Calling an existing Initialization Method in another initialization method is called designated initializer.

5. nslog is the standard output in OC. When the date, time, and application name are appended to the output. When nslog () is used to output the value of any object, % @ format is used. When this specifier is used, the object uses a method named description to provide its own nslog () format.

Using @ property with @ synthesize enables the compiler to automatically implement the getter/setter method, which is convenient to use and can directly use the object. property "method call; if we want to" object. method "to call a method and obtain the return value of the method, you need to use @ property with @ dynamic.

Use@ DynamicThe keyword tells the compiler to implement the access method by ourselves. If @ synthesize is used, the working compiler will help you implement it.

ReadonlyThis tag indicates that the attribute is read-only, and the default tag is read/write. If you specify read-only, you only need one reader in @ implementation. Or if you use the @ synthesize keyword, the reader method is parsed. And if you try to assign values to attributes using the vertex operator, you will get a compilation error.

ReadwriteThis tag indicates that the attribute is read/write, which is also the default attribute. Both the configurator and reader must be implemented in @ implementation. If the @ synthesize keyword is used, the reader and the setter are parsed.

Nonatomic: Non-atomic access, no lock when assigning values to attributes, multi-thread concurrent access will improve performance. If this attribute is not added, both access methods are atomic transaction access by default.

Atomic and nonatomic are used to determine whether the getter and setter generated by the compiler are atomic operations.

Atomic
When setting the @ property attribute of a member variable, the default value is atomic, providing multi-thread security.
In a multi-threaded environment, atomic operations are necessary; otherwise, errors may occur. With Atomic added, the setter function will become as follows:
{Lock}
If (property! = Newvalue ){
[Property release];
Property = [newvalue retain];
}
{Unlock}
Nonatomic
Multithreading and Variable Protection are prohibited to improve performance.
Atomic is a thread protection technology used by objc. It basically prevents reading data by another thread when the write is not completed, resulting in data errors. This mechanism consumes system resources. Therefore, nonatomic is a good choice for small devices such as the iPhone, if multi-thread communication programming is not used.
It indicates that accessors are not atomic operations, but by default, accessors are atomic operations. That is to say, in a multi-threaded environment, the parser provides a secure access to the attributes. The returned values obtained from the reader or the values set by the setter can be completed at one time, even other threads are accessing it. If you do not specify nonatomic, the resolved accessors retain and automatically release the returned values in the memory management environment. If nonatomic is specified, the accessors simply return this value.

Assign: Simple assignment without changing the index count
Applicable to basic data types (such as nsinteger, cgfloat) and C data types (INT, float, double, Char, etc.)

This flag indicates that the setter directly assigns a value, which is also the default value. In applications that use garbage collection, if you want an attribute to use assign and the class complies with the nscopying agreement, you need to specify this tag rather than simply using the default value, otherwise, you will get a compilation warning. This again shows to the compiler that you really need to assign values, even if it is copyable.

Copy:Create an object with an index count of 1 and release the nsstring

It indicates to nsstring that a copy of the input value is used when the value is assigned. The copy operation is executed by the copy method. This attribute is only valid for object types that implement the nscopying protocol. For more information, see "copy.

Retain: Release the old object, assign the value of the old object to the input object, and increase the index count of the input object to 1.
For other nsobject and its subclass

Perform the release old value for the parameter, and then retain the new value.
The specified retain will wake up the retain message of the input value when the value is assigned. This attribute can only be used for the objective-C object type, but not for the core foundation object. (The reason is obvious: retain will increase the reference count of the object, and neither the basic data type nor the core foundation object has reference count-Translator's note ).
Note: when an object is added to an array, the reference count increases the number of object references by more than 1.

The actual retain syntax is:
-(Void) setname :( nsstring *) newname {
If (name! = Newname ){
[Name Release];
Name = [newname retain];
// Name's retain count has been bumped up by 1
}
}

Copy and retain:

Copy actually creates the same object, and retain is not:
For example, an nsstring object with the address 0 × 1111 and the content @ "STR"
After copying data to another nsstring, the address is 0 × 2222, the content is the same, the new object retain is 1, and the old object does not change
After retain reaches another nsstring, the address is the same (create a pointer and copy the pointer), and the content is of course the same. The retain value of this object is + 1
That is to say, retain is a pointer copy and copy is a content copy. Wow, it's much easier than you think...

Retain's set method should be light replication, and the copy's set method should be deep replication.

Another usage of copy:
Copy is a copy of the content, which is true for nsstring.
But what if we copy an nsarray? For example,
Nsarray * array = [nsarray arraywithobjects: @ "hello", @ "world", @ "baby"];
Nsarray * array2 = [array copy];
At this time, the system indeed opened up a memory space for array2, but we need to realize that each element in array2 only copies the pointer to the corresponding element in the array. this is the so-called "Shallow replication ".

Assign and retain:

1. if you have been in contact with C, assume that you have allocated a piece of memory with malloc and assigned its address to pointer A. Later, you want pointer B to share the same piece of memory, so you assigned a to (assign) B again. At this time, a and B point to the same memory. Can a directly release this memory when a no longer needs it? The answer is no, because a does not know whether B is still using this memory. If a is released, B will cause crash when using this memory.

2. I learned about the assign problem in 1. How can I solve it? The simplest way is to use reference counting. In the example above, we set a reference count for the memory. When the memory is allocated and assigned to, the reference count is 1. When a is assigned to B, the reference count is increased to 2. If a no longer uses this memory, it only needs to reduce the reference count by 1, indicating that it no longer owns this memory. When B no longer uses this memory, it also reduces the reference count by 1. When the reference count is 0, it indicates that the memory is no longer referenced by any pointer, and the system can release it directly.

Conclusion: The above two points are actually the differences between assign and retain. Assign is a direct value assignment, which may cause problems in 1. When the data is of native types such as int and float, assign can be used. As described in section 2, retain uses the reference count. Retain causes the reference count to increase by 1, and release causes the reference count to decrease by 1. When the reference count is 0, the dealloc function is called, memory is recycled.

Nsstring * PT = [[nsstring alloc] initwithstring: @ "ABC"];
The above code executes the following two actions:
1. Allocate a block of memory on the heap to store @ "ABC". For example, if the memory address is 0x1111, the content is "ABC"
2. Allocate a block of memory on the stack to store pt. For example, the address is 0 xaaaa and the content is naturally 0x1111.
Next, let's take a look at assign retain copy.
Assign: nsstring * newpt = [PT assing];
At this time, the addresses of newpt and PT are completely the same. The content of 0 xaaaa is 0x1111, that is, newpt is only the alias of PT, and any operation is equivalent to another operation. Therefore, retaincount does not need to be added.
Retain: nsstring * newpt = [PT retain];
At this time, the newpt address is no longer 0 xaaaa, which may be 0 xaabb but the content is still 0x1111. Therefore, both newpt and Pt can manage the memory where "ABC" is located. Therefore, retaincount needs to be increased by 1.
Copy: nsstring * newpt = [PT copy];
In this case, a memory segment will be re-opened on the stack to store @ "ABC". For example, if 0x1122 is @ "ABC, a space such as the address will be allocated to newpt on the stack: the content of 0 xaacc is 0x1122. Therefore, retaincount is increased by 1 for newpt to manage the memory segment 0x1122.

//--------------------------
After reading so much, you may be a little dizzy. Now we will demonstrate the actual code:

@ Property (nonatomic, assign) int number;
An attribute of the int type is defined here, so this int is a simple data type and can be considered as an atomic access. Therefore, we use nonatomic instead of reference counting, so we use assign. Applicable to All simple data types.

@ Property (nonatomic, copy) nsstring * mystring;
An nsstring attribute is defined here, and no atomic operation is required. Therefore, nonatomic is used.
Why copy instead of retain! If you assign a value to mystring, the original string is a variable string (nsmutablestring) object, and you use retain, when the original string changes, your mystring attribute will also change. I don't think you want to see this phenomenon. In practice, if the original string is nsstring, it will only be retained, and no copy will be copied.

@ Property (nonatomic, retain) uiview * myview;
An attribute of the uiview type is defined here, and no atomic operation is required. Therefore, nonatomic is used.
When assigning values to myview, the original uiview object retaincount will add 1

// Interface file
@ Interface myclass: nsobject
@ Property (nonatomic, assign) int number;
@ Property (nonatomic, copy) nsstring * mystring;
@ Property (nonatomic, retain) uiview * myview;
@ End

// Implementation file
@ Implementation myclass
@ Synthesize number;
@ Synthesize mystring;
@ Synthesize myview;

// Release the memory
-(Void) dealloc
{
[Mystring release]; // the attribute of copy must be release;
[Myview release]; // release is required for retain attributes;

[Super dealloc]; // returns the parent object
}

@ End

Assume that you have a piece of code to create a myclass object

Myclass * instance = [myclass alloc] init];

// Assign a value to number. There is nothing to say. This is the case for simple data types.
Instance. Number = 1;

// Create a variable string
Nsmutablestring * string = [nsmutablestring stringwithstring: @ "hello"];

Instance. mystring = string; // assign values to mystring

[String appendstring: @ "world! "]; // Append text to string

Nslog (@ "% @", string); // here the string has changed and the output is "Hello World !"

Nslog (@ "% @", instance. mystring); // output mystring, you will find that the output here is still "hello" because mystring has copied a copy before the string changes

Uiview * view = [[uiview alloc] init];
Nslog (@ "retaincount = % d", view. retaincount );
// Output reference count of the view, which is 1 at this time

Instance. myview = view; // assign values to the myview attribute

Nslog (@ "retaincount = % d", view. retaincount );
// Output the reference count of the view again, which is 2 at this time, because the view is retained once by myview.

[View release];
// Although the view is released by release, the object pointer of the uiview retained by myview is still valid even if the view is retained by myview.

[Instance release];

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.