IOS keywords self,super,copy, retain, assign, ReadOnly, ReadWrite, Nonatomic, @synthesize, @property, @dynamic

Source: Internet
Author: User

IOS Key Words Self,super , copy, retain, assign, ReadOnly, ReadWrite, Nonatomic ,

@synthesize , @property , @dynamic

#synthesize关键字: According to the @property setting, the corresponding access method of the member variable is automatically generated, so that the member variable can be conveniently accessed using the point operator.

@implementation keyword that indicates that the implementation of the class @end ended

The Self keyword: similar to this in Java, is a hidden parameter that points to the class of the currently calling method.

Super Keyword: Invokes the method of the parent class.

Self = [Superinit] Here is not to judge whether self is equal to [superinit], but to determine whether it can be initialized successfully. [Super Init]: When the parent class is initialized successfully, by = to self, so that self becomes a non-empty object, the whole is not false (not no).

#import tells the preprocessor to include the contents of the header file in this file. The import in OC guarantees that the header file will only be included once [email protected] Keyword: Declare a student class. @end End statement.

Colon: Indicates that inheritance is followed by the parent class.

NSObject is the memory management, and initialization framework, as well as reflection and type operations that most objects will use. Equivalent to object.

NS is the nextstep abbreviation, which indicates that this function is from the Cocoa Toolkit.

    1. Declare global variables, as in C.
    2. Property Keyword: Sets the properties of the member variable (with read/write, assignment assign,retain,copy, and support for multithreading nonatomic).
    3. Declares a method with a format of-(return value) method keyword 1: (parameter type) parameter name Method Keyword 2: (parameter type) parameter name ... (You can find the method keyword to determine the parameters when you read the method).

-Minus is an instance method, + is a class method

4. The concept of invoking an existing initialization method in another initialization method is called designated Initializer.

5. NSLog is the standard output in OC, the additional output is date, time, and application name. When you use NSLog () to output values for any object, you use the%@ format description. When using this specifier, the object provides its own nslog () format through a method called description.

Using @property with @synthesize allows the compiler to automatically implement the Getter/setter method, which is convenient when used, and can be directly used by the "object. Properties" method call; If we want "object. Method" Way to call a method and get the return value of the method, you need to use @property mate @dynamic.

Using @dynamic keyword tells the compiler to implement the access method by ourselves. If you are using @synthesize, then this work compiler will do it for you.

readonly This tag indicates that the property is read-only, the default tag is read-write, and if you specify read-only, only one reader is required in @implementation. Or if you use the @synthesize keyword, there is also a reader method that is parsed. And if you try to assign a value to a property using the dot operator, you'll get a compilation error.

ReadWrite This tag indicates that the property is read-write, which is also the default property. Both the setup and the reader need to be implemented in @implementation. If you use the @synthesize keyword, both the reader and the setup are parsed.

nonatomic: Non-atomic access, when assigning values to attributes without locking, multi-threaded concurrent access improves performance. If this attribute is not added, the default is two access methods are atomic transaction access.

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

Atomic

When you set the @property property of a member variable, the default is atomic, which provides multithreading security.

In a multithreaded environment, atomic operations are necessary, otherwise they may cause incorrect results. Adding the Atomic,setter function will change to the following:

{Lock}

if (Property! = newvalue) {

[Property release];

property = [NewValue retain];

}

{Unlock}

Nonatomic

Prohibit multi-threading, variable protection, improve performance.

Atomic is a thread-protection technique used by OBJC, basically to prevent the data from being read by another thread when the write is not completed. This mechanism is resource-intensive, so nonatomic is a very good choice on small devices such as the iphone, if there is no communication programming between multiple threads.

Indicates that the accessor is not an atomic operation, and the accessor is an atomic operation by default. This means that, in a multithreaded environment, the parsed accessor provides a secure access to the property, the return value obtained from the picker, or the value set by the setting can be done at once, even if another thread is accessing it. If you do not specify nonatomic, the parsed accessor retains and automatically releases the returned value in the environment in which it manages the memory, and if nonatomic is specified, the accessor simply returns the value.

Assign: Simple assignment, not changing index count

Simple data types for underlying data types (such as nsinteger,cgfloat) and C data types (int, float, double, char, etc.)

This flag indicates that the setting is assigned directly, which is also the default value. In an application that uses garbage collection, if you want a property to use assign, and this class conforms to the nscopying protocol, you should explicitly indicate this tag instead of simply using the default value, otherwise you will get a compile warning. This again explains to the compiler that you really need to assign a value, even if it is a copy.

copy: Create an object with an index count of 1 and then release the old object to NSString

For NSString it states that a copy of the passed-in value is used when the value is assigned. Copy work is performed by the copy method, and this property is valid only for those object types that implement the Nscopying protocol. For a more in-depth discussion, refer to the "Copying" section.

retain: Frees the old object, assigns the value of the old object to the input object, and then increases the index count of the input object to 1

For other NSObject and its subclasses

Release the old value of the parameter, and then retain the new value

Specifies that retain will wake the retain message of the incoming value when the value is assigned. This property can be used only for Objective-c object types, not for core Foundation objects. (for obvious reasons, retain increases the object's reference count, and neither the base data type nor the core Foundation object has a reference count-the translator's note).

Note: When you add an object to an array, the reference count increases the number of references to the object by +1.

The actual syntax for retain is:

-(void) SetName: (NSString *) NewName {

if (name! = NewName) {

[Name release];

name = [NewName retain];

Name ' s retain count have been bumped up by 1

}

}

Copy with the retain :

Copy actually creates an identical object, and retain is not:

such as a NSString object, the address is 0x1111, the content is @ "STR"

Copy to another nsstring, the address is 0x2222, the content is the same, the new object retain is 1, the old object has not changed

Retain to another nsstring, the same address (set up a pointer, pointer copy), the content of course the same, the object's retain value +1

That is, retain is a pointer copy and copy is a copy of the content. Wow, it's a lot easier than you think.

The set method of retain should be shallow copy, copy's set method should be deep copy

Copy another usage:

Copy is a copy of the content, which is true for like NSString.

But what if copy is a Nsarray? for example,

Nsarray *array = [Nsarray arraywithobjects:@ "Hello" @ "World" @ "Baby"];

Nsarray *array2 = [array copy];

At this point, the system does open up a memory space for array2, but what we realize is that each element in the array2 is simply a copy of a pointer to the corresponding element in the array. This is called "shallow copy."

Assign with the retain :

1. Contact C, then assume that you allocate a piece of memory with malloc, and assign its address to pointer a, and then you want pointer b to share the memory, so you assign a value to (assign) B. At this time A and B point to the same piece of memory, I ask when a no longer need this memory, can you directly release it? The answer is no, because a does not know whether B is still using this memory, and if A is released, then B will cause the program to crash when it uses this memory.

2. Understand the problem of assign in 1, then how to solve? The simplest method is to use a reference count (reference counting), or the above example, we set a reference count for that memory, and when the memory is assigned and assigned to a, the reference count is 1. The reference count increases to 2 when a is assigned to B. If a no longer uses this memory, it only needs to subtract the reference count by 1, indicating that it no longer owns the memory. b The reference count is also reduced by 1 when the memory is no longer used. When the reference count becomes 0, the memory is no longer referenced by any pointers, and the system can release it directly.

Summary: The above two is actually the difference between assign and retain, assign is the direct assignment, which may cause 1 of the problem, when the data is int, float and other native types, you can use assign. Retain as described in 2, using a reference count, retain causes a reference count plus 1, release causes a reference count minus 1, when the reference count is 0 o'clock, the Dealloc function is called and memory is recycled.

NSString *pt = [[NSString alloc] initwithstring:@ "abc"];

The preceding section of code performs the following two actions

1 Allocate a piece of memory on the heap to store @ "abc" such as: Memory address: 0x1111 content is "abc"

2 Allocate a piece of memory on the stack to store PT for example: Address: 0Xaaaa Content Naturally 0x1111

Below see the Assign retain copy

Assign situation: NSString *NEWPT = [pt assing];

At this point NEWPT and PT are exactly the same address is 0XAAAA content 0x1111 that is newpt is just the alias of PT, for any one operation is equal to another operation. Therefore Retaincount does not need to increase.

Retain situation: NSString *NEWPT = [pt retain];

At this point the address of NEWPT is no longer 0Xaaaa and may be 0Xaabb but the content is still 0x1111. So both NEWPT and PT can manage the memory where "ABC" is located. So Retaincount needs to increase by 1.

Case of copy: NSString *NEWPT = [pt copy];

At this time, the heap will be re-opened a memory storage @ "ABC" such as 0x1122 content is @ "ABC will also be on the stack for the NEWPT allocation of space such as address: 0XAACC content is 0x1122 so retaincount add 1 for NEWPT to manage 0x1122 this memory

——————————————————————————

Seeing so many people may be a little dizzy, now do the actual code demo:

@property (nonatomic, assign) int number;

This defines a property of type int, then this int is a simple data type, it can be considered as atomic access, so with nonatomic, there is no need for reference counting, so use assign. Applies to all simple data types.

@property (nonatomic, copy) NSString * myString;

This defines an attribute of type NSString and does not require atomic manipulation, so use nonatomic.

Why copy is needed, not retain! Because if the MyString assignment original string is a mutable string (nsmutablestring) object, with retain, your mystring property will be changed when the original string changes. I don't think you want to see this phenomenon. Actually BO Master test, if the original string is NSString, but also just retain, and will not copy copy

@property (nonatomic, retain) UIView * MyView;

This defines an attribute of type UIView and does not require atomic manipulation, so use nonatomic.

When assigning a value 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;

Freeing memory

-(void) dealloc

{

[MyString release]; The Copy property needs to be release;

[MyView release]; The attributes of retain need to be release;

[Super Dealloc]; Returns the parent object

}

@end

If you have a piece of code that creates a MyClass object

MyClass * instance = [MyClass alloc] init];

Number assignment, nothing to say, simple data type just like that

Instance.number = 1;

Create a mutable string

nsmutablestring * string = [nsmutablestring stringwithstring:@ "Hello"];

instance.mystring = string; Assigning 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);

The reference count of the output view, at this time 1

Instance.myview = view; Assigning a value to the MyView property

NSLog (@ "Retaincount =%d", view.retaincount);

Output the view's reference count again, at this time at 2, because MyView has a retain on the view.

[View release];

Although the view was released by release, but MyView retain the view once, the myview reserved UIView object pointer is still valid.

[Instance release];

IOS keywords self,super,copy, retain, assign, ReadOnly, ReadWrite, Nonatomic, @synthesize, @property, @dynamic

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.