About the properties of @property () and about ARC

Source: Internet
Author: User

@property () commonly used properties are: Nonatomic,atomic,assign,retain,strong,weak,copy.

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

NSObject the @property property of an object, 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:
Nslock *_lock =lock   if (Property! = newvalue) {
[Property release];
property = [NewValue retain];
}[-lock 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.

Nonatomic 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

For the underlying data type (nsinteger,cgfloat) and the C data type (int, float, double, char), and so on.
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.

Retain
Release the old value of the parameter to the other nsobject and its subclasses, 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.

Copy
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.

Copy and retain:

Copy actually creates an identical object, and retain is not:
1. For example a NSString object, the address is 0x1111, the content is @ "STR", Copy to another nsstring after the address is 0x2222, the content is the same.

2. The new object retain is 1, the old object has not changed retain to another nsstring after the same address (set up a pointer, pointer copy), the contents of course the same, the object's retain value +1.
Summary: Retain is a pointer copy and copy is a copy of the content.

Assign and 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.

Strong and weak

Before we introduce strong and weak, let's start with the arc mechanism.

ARC is a new feature that has been added since iOS 5, completely eliminating the cumbersome manual management of memory, and the compiler will automatically insert the appropriate retain, release, and autorelease statements where appropriate. You no longer need to worry about memory management, because the compiler handles everything for you

Note: ARC is a compiler attribute, not an IOS runtime feature (except for the weak pointer system), and it is not similar to a garbage collector in other languages. So ARC and manual memory management performance is the same, and sometimes faster, because the compiler can also perform some optimizations

Arc principle

The rules of ARC are very simple: as long as there is another variable pointing to the object, the object remains in memory. When the pointer points to a new value, or if the pointer no longer exists, the associated object is automatically freed. This rule is applicable for instance variables, synthesize attributes, and local variables.

Strong Pointer

There is a text input box property in the controller

@property (nonatomic, assign) Iboutlet Uitextfield *namefield;  

1. If the user enters the MJ string in the text box

Then it can be said that the text property of the Namefield is a pointer to the NSString object, which is the owner, which holds the contents of the Text input box

2. If the following code is executed

NSString *name = Self.nameField.text;  

An object can have multiple owners, and in the code above, the name variable is also the owner of the NSString object, which means that there are two pointers pointing to the same object

3. The user then changes the contents of the input box, such as

At this point, the Text property of Namefeild points to the new NSString object. However, the original NSString object still has an owner (name variable), so it will remain in memory

4. When the name variable gets a new value, or no longer exists (such as when the local variable method returns, the instance variable object is released), the original NSString object no longer owns any owners, and the retain count drops to 0, when the object is freed

For example, assign a new value to the name variable

@" Jake ";

We call the name and Namefield.text pointers "strong pointers" because they maintain the life of the object. Default all instance variables and local variables are strong pointers

Weak pointer

A pointer variable of type weak can still point to an object but not to the owner of the object

1. Execute the following code

__weak nsstring *name = Self.nameField.text;

The name variable and the Namefield.text attribute both point to the same NSString object, but name is not the owner

2. If the contents of the text box change, then the original NSString object will not have the owner, will be released, the name variable will automatically become nil, called the null pointer

The weak pointer variable automatically becomes nil, which prevents the weak pointer from continuing to point to the disposed object, avoids the creation of a wild pointer, or causes a very difficult-to-find bug, with null pointers eliminating similar problems.

The 3.weak pointer is primarily used for the "parent-child" relationship, where the father has a strong pointer to the son, so the father is the owner of the son, but in order to prevent the cycle of ownership, the son needs to use the weak pointer pointing to his father. A typical example is the delegate mode, where your viewcontroller has a uitableview through the strong pointer (Self.view), UITableView DataSource and delegate are weak pointers, Point to your Viewcontroller

Strong and weak pointers for use note

1. The following code is problematic:

__weak nsstring *str = [[NSString alloc] Initwithformat:@ "1234"];  NSLog (@ "%@"//  print out yes "(null)"  

STR is a weak pointer, so the NSString object has no owner and is released immediately after creation. Xcode will also give a warning ("warning:assigning retained object to weak variable; Object would be released after assignment ")

2. The general pointer variable is strong type by default, so we generally do not add __strong to the strong variable, the following two lines of code are equivalent:

NSString *name = self.nameField.text;  

3. Attributes can be strong or weak, as follows

@property (nonatomic, Strong) NSString *name;   ID delegate;  

4. The following code may not work before arc, because in manual memory management, when an object is removed from Nsarray, the object sends a release message and may be released immediately. Subsequent nslog () printing of the object will cause the app to crash.

ID obj = [array objectatindex:0];  [Array Removeobjectatindex: 0 ];  NSLog (@ "%@", obj);  

This code is perfectly legal in arc because the obj variable is a strong pointer that becomes the owner of the object, and removing the object from the Nsarray does not cause the object to be freed

Arc Summary

1. With arc, our code can be much clearer and you no longer have to think about when to retain or release objects. The only thing to consider is the association between objects, which object has which object?

2.ARC also has some limitations:

1> first arc works only with Objective-c objects, and if your app uses Core Foundation or malloc ()/free (), you need to manually manage the memory at this point

2> In addition to the arc there are some other stricter language rules to ensure that arc works properly

3. Although Arc manages retain and release, it doesn't mean you don't have to worry about memory management at all. Because the strong pointer maintains the life of the object, in some cases you still need to manually set these pointers to nil, which may cause the app to be out of memory. Whenever you create a new object, you need to consider who owns the object and how long the object needs to survive

4.ARC can also be used in conjunction with C + +, which is very helpful for game development. There is a little bit of restriction on iOS 4,arc (weak pointers are not supported), but it doesn't matter much

Arc Use note Summary

1. Cannot call the Dealloc method directly, cannot call the Retain,release,autorelease,retaincount method, including @selector (retain) Not in the same way. 2. You can use the Dealloc method to manage some resources, but not to release the instance variable, nor to remove the [super Dealloc] method inside the Dealloc method, the dealloc of the parent class under Arc is also automatically completed by the compiler 3.Core Object of foundation type can still be used Cfretain, Cfrelease these methods 4. Nsallocateobject and Nsdeallocateobject objects can no longer be used 5. Object pointers cannot be used in a C struct, and if there is a similar function you can create a objective-c class to manage these objects 6. No between ID and void* A simple conversion method, as well as a conversion between the OBJECTIVE-C and core foundation types, requires a compiler-developed conversion function 7. The NSAutoreleasePool object can no longer be used, ARC provides @ Autoreleasepool block to replace it, This is more efficient 8. Cannot use memory store (no longer use Nszone) 9. You cannot give a property a name of 10 by starting with new. When declaring iboutlet, you should generally use weak, except for storyboard, the top-level object in the middle of the nib to use strong11.weak equivalent to the old version of a Ssign,strong equivalent to retain reference link: http://blog.csdn.net/q199109106q/article/details/8565017

About the properties of @property () and about ARC

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.