Differences in IOS Property modifiers

Source: Internet
Author: User
Tags modifiers

Objective
All development before IOS5 requires the developer to control the reference and release of their own objects. The modifiers used are assign, copy, retain
After IOS5, Apple introduced the arc (automatic reference counting) mechanism, introduced a new modifier to replace the previous modifier strong, weak

Simple description
In 1:ARC environment, strong instead of Retain.weak instead of assign
2:weak: In the ARC environment, all weak pointers pointing to this object will be set to nil. This t feature is useful, and it is believed that many developers have been plagued by the exc_bad_access of pointers to objects that have been disposed of, and that after using arc, either strong or weak type pointers will no longer point to an object that has been destroyed. It fundamentally solves the crash caused by accidental release. 3:assign: Simple assignment, does not change reference count, applies simple data types to underlying data types (such as nsinteger,cgfloat) and C data types (int, float, double, char, etc.)
4:copy: Create an object with an index count of 1 and then release the old object
5:strong: In an ARC environment, the object is not destroyed as long as an object is pointed to by a strong pointer. If the object is not pointed to by any strong pointer, it will be destroyed. By default, all instance variables and local variables are of type strong. It can be said that the strong type of the pointer in the behavior with non-arc under the retain is more similar
6:retain: In the non-arc era, you need to retain an object that you want to keep, which is not required in the ARC environment. Now the only thing to do is to point to the object with a pointer, and as long as the pointer is not reset to NULL, the object will always be on the heap. When the pointer points to the new value, the original object will be release once. This is useful for instance variables, sunthesize variables, or local variables.

Examples Show

1: @property (nonatomic, assign) NSString *title;

What is the difference between assign,copy,retain?

Assign: Simple assignment, without changing the index count (Reference counting).

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

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

The difference between 2:weak and strong:

The difference (weak and strong) is that when an object no longer has a strong type pointer pointing to it, it is freed, even if there is a weak pointer to it.

Once the last strong pointer is left, the object will be released and all remaining weak pointers will be cleared.

There may be an example to describe it as appropriate.

Imagine our object is a dog, the dog wants to run Away (be released).

The strong type pointer is like a tethered dog. As long as you hang the dog with a leash, the dog will not run away. If there are 5 people holding a dog (5 strong pointers pointing to 1 objects), the dog will not run away unless 5 of the ropes fall off.

The weak type pointer is like a child pointing at the dog and shouting: "Look!" A dog is there. "As long as the dog is kept tied, the child can see the dog, and the (weak pointer) will always point to it. As long as the dog's leash comes off, the dog will run away, no matter how many children are watching it.

As long as the last strong pointer no longer points to the object, the object is freed and all weak pointers are cleared.

Usage Scenarios

1: Use assign: for underlying data types (nsinteger,cgfloat) and C data types (int, float, double, char, and so on)

2: Use copy: to NSString

3: Use retain: For other nsobject and its subclasses

4:strong and weak

Strong is used to modify properties of strong references;

@property (Strong) SomeClass * aobject;

corresponding to the original
@property (Retain) SomeClass * aobject; and @property (copy) SomeClass * aobject;

Weak is used to modify the properties of weak references;
@property (weak) SomeClass * aobject;
corresponding to the original

@property (assign) SomeClass * aobject;

5:nonatomic Keywords:

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.

Complementary basics

iOS objects are inherited from NSObject, which has a method: Retaincount, memory reference count. Reference counting is used in many techniques: COM components under window, multi-threaded semaphores, read and write locks, and thought alike.


(General: Exceptions are discussed later)
Alloc object is assigned a reference count of 1
Reference count for retain objects +1
Copy copy of an object into a new object (new memory address) reference count of 1 original object count unchanged

Release object reference count-1 if 0 frees memory
Autorelease object reference count-1 if 0 is not released immediately, released at the nearest pool
NSLog (@ "smessage retaincount:%u", [smessage Retaincount]);

The principle of memory management is to balance the final reference count,
Memory leaks If last reference count is greater than 0
If the reference count equals 0 also operates on the object, memory access failure occurs, crash so try to set as nil
Both of these problems are serious, so be sure to pay attention to memory release and set to nil after use

member variables and properties
It's not as simple as it is, you might need to call another function to assign a variable in one function.
There are two choices: class member variables and usage properties
@interface Testmem:nsobject {
Testobject *m_testobject; Member variables
Testobject *testobject; Member variables
}
The member variables are consistent with the memory management above, but the balance of reference count plus and minus is maintained in different functions.
So you have to check each time you assign the last time you've been assigned. Is it possible to invoke
When do I use attributes?
1. Make the members public.
2. Outlet is generally declared as a property (this memory is in the system control, but we should still do the same operation, will speak later)
3. If many functions need to change this object, or the function triggers many times, it is recommended to use attributes. Let's see what it looks like when the property function expands:

Assign
-(void) Settestobject:(ID) newvalue{
Testobject= NewValue;
}
Retain
-(void) Settestobject:(ID) newvalue{
if (testobject!= newvalue) {
[Testobject release];
testobject= [newvalue retain];
}
}
Copy
-(void) Settestobject:(ID) newvalue{
if (testobject! = newvalue) {
[Testobject release];
Testobject = [newvalue copy];
}
}
Asssign relative to the pointer assignment, do not operate the reference count, note that the original object is not necessary, be sure to set this to nil
Retain equivalent to the reference count of the original object plus 1
Copy does not change the reference count of the original object, generating a new object reference count of 1
Attention:
The Settestobject method is called by the Self.testobject Lvalue. The right value is the Get method, and the Get method is relatively simple.
Instead, the Testobject uses a member variable
Self.testobject = [[Testobject alloc] init]; Wrong Reatin two times
Testobject = [Nsarray objectbyindex:0]; It's not safe, there's no retain back, release will go wrong.
If Testobject already has a value, it will be mem leak

Automatically manage objects
IOS provides a lot of static (+) class methods for creating objects, which are statically, and can be directly used with the class name
Calls such as:
NSString *teststring = [nsstring stringwithformat:@ "test"];
TestString is an automatically managed object, you don't have to relese him, he has a big retain count, and the number does not change after release.

Exception
Some of the objects generated by Alloc are automatically managed as follows:
NSString *teststring = [[NSString alloc] initwithstring:@ "test1"];
Retain count is also a large number, no way to release
But for the code to correspond, still should add [teststring release];
Otherwise Xcode's analyze will recognize the memory leak, but instruments leak tool detection is not

Cocoa Autorelease in different memory management environments
H Mixed Memory Management Environment: garbage collection Method (garbage Collection) + Index counting method (Reference counting)
While in most cases a mixed environment is not recommended, if in this case autorelease need to be aware of the following:
Garbage collection mixed environment: the drain method should be used because release has no meaning in GC mode
Index count Environment: Drain and release have the same effect for Autoreleasepool (auto-free pool)

The misunderstanding of Autorelease
The memory management of a cocoa is divided into the index count method (Reference Counting/retain count) and the garbage collection method (garbage Collection). The iphone only supports the former, so Autorelease has become a "shortcut" for many people.
But! Autorelease is not actually "automatically released", unlike garbage collection, the relationship between objects detected after detection of garbage-delete. But Autorelease is actually "delayed release", which is marked as autorelease after a running cycle and is released.
Remember to use autorelease carefully, understand autorelease, and prevent it from being released by the system when you still need the object.

Memory management issues with Interface Builder involvement
Points:
If a variable is defined in the class in order to Iboutlet then you do not need to instantiate it, the xib loader initializes it.
If a variable is defined in the class in order to Iboutlet then you have to be responsible for releasing it. Xib loader will not help ...
* Do not initialize two back, memory will overflow, and object lock will be error.

Questions about index count (Reference counting)

1. *retain value = Index count//(Reference counting)

The Nsarray object retain the object in any array (retain value plus one). When Nsarray is unloaded (Dealloc), all objects in the array are freed once (the retain value is reduced by one). Not only Nsarray, but any collection class (Collection Classes) performs a similar operation. such as nsdictionary, or even uinavigationcontroller.
Alloc/init the object that is created, the index count is 1. No need to retain it again.
Methods such as [Nsarray array] and [NSDate Date] Establish an object with an index count of 1, but it is also an automatic release object. So it's a local temporary object, so it doesn't matter. If you are a variable (IVAR) that you intend to use in a full class, you must retain it.
The default class method return value is executed with the "auto-release" method. (* Nsarray in the above)
In the Unload method "Dealloc" in the class, release all the NS objects that are not balanced. (* All not autorelease, while retain value is 1)

NSString Memory Management
The following example:

1. astring = @ "I am a string, 2 years old, man!";

In this case, the string is stored and managed by the system, and we don't have to worry about it.

astring = [NSString stringwithformat:@ "I am a string,%d years old, man!", 2];

In the second case, we need to go to retain and release this string, regardless of the system.

OBJECTIVE-C Memory Management
You initialize (Alloc/init) The object and you need to release it (release). For example:

Nsmutablearray Aarray = [[Nsarray alloc] init];

[Aarray release];

2, you retain or copy the, you need to release it. For example:

[Aarray retain]

After the need

[Aarray release];

3, the object that is passed (assign), you need to consider the retain and release. For example:

Obj2 = [[Obj1 somemethod] autorelease];

Object 2 receives an automatically freed value of object 1, or passes a base data type (nsinteger,nsstring): You or you want to retain object 2 to prevent it from being automatically freed before it is used. But after retain, be sure to release it at the right time.

Why can't I just call dealloc instead of release?
Dealloc not equal to Free,dealloc in C does not release memory, nor does it degrade the index count (Reference counting). So the direct call to Dealloc instead of freeing memory.
In Objective-c, the index count plays a decisive role.

Differences in IOS Property modifiers

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.