iOS strong, weak, assign, copy

Source: Internet
Author: User
Tags shallow copy

Copy and strong (retain) differences

1. http://blog.csdn.net/itianyi/article/details/9018567

Most of the time NSString properties are copy, then copy and strong in the case of what is the difference?

Like what:

@property (retain,nonatomic) NSString *rstr;

@property (copy, nonatomic) NSString *cstr;

-(void) test:

{

nsmutablestring *mstr = [nsmutablestringstringwithformat:@ "abc"];

Self.rstr = MSTR;

Self.cstr = MSTR;

NSLog (@ "mstr:%p,%p", mstr,&mstr);

NSLog (@ "retainstr:%p,%p", _rstr, &_RSTR);

NSLog (@ "copystr:%p,%p", _cstr, &_CSTR);

If the address of the MSTR object is 0x11, that is, 0x11 is the first address of the @ "abc", the MSTR variable itself has an address of 0x123 in memory;

When assigning MSTR to retain Rstr, the Rstr object's address is the 0X11,RSTR variable itself in memory address 0x124;rstr and MSTR point to the same address, they point to the same object @ "ABC", the object's address is 0x11, So their values are the same.

When assigning MSTR to copy's CStr, the CStr object's address is 0X22,CSTR variable itself in memory address 0x125;cstr and MSTR point to the address is not the same, they point to a different object, so copy is a deep copy, a new object, The address of this object is 0x22 and the value is @ "abc".

If you change the value of MSTR now:

[Mstr appendstring:@ "de"];

NSLog (@ "retainstr:%@", _rstr);

NSLog (@ "copystr:%@", _cstr);

Results

The value of the string rstr using retain: @ "ABCDE",

And the value of the string CStr using copy: @ "abc",

So, in general, we don't want string values to follow mstr, so we generally use copy to set the string's properties.

If you want the value of the string to follow the value of the assigned string, you can use Strong,retain.

Note: The above situation is for when the nsmutablestring assignment to NSString, the time will be different, if the assignment is NSString object, then use Copy or strong, the result is the same, Because the NSString object simply cannot change its value, he is immutable.

Assign an object to an attribute variable, and when the object changes, use the strong property if you want the property variable to change, or use the Copy property if you want the property variable to change.

From this we can see:

The source is a string of nsmutablestring, retain is merely a pointer reference, adding a reference counter, so that when the source changes, the variable declared in this retain way (whether the assigned variable is variable or immutable), it will follow the change; and copy declares the variable, it does not follow the source change, it is actually a deep copy.

The source is a string of nsstring, whether it is a variable declared by the retain or copy declaration of the variable, when the second source of the string again points to another place, it still points to the original position, that is, both are pointer references, that is, a shallow copy.

Also, the effect of both on memory counts is the same, which increases the memory reference count, which needs to be handled at the end of the day.

In fact, why should the string be used in these two ways? I think it is still a security issue, such as the declaration of a NSString *str variable, and then the assignment of a nsmutablestring *mstr variable to it, if you want STR to follow the MSTR change, then use retain; If Str cannot change with MSTR, then copy is used. And for the NSString type of string to be assigned to STR, those two are no different. Does not affect security, as is memory management.

2.

IosObjects are inherited from theNSObject,The object has a method: RetaincountA memory reference count. Reference counting is used in many technologies: WindowUnder theComcomponents, multi-threaded semaphores, read and write locks, the idea is the same.

( general : alloc object is assigned a reference count of 1
retain reference count of objects +1
Copy copy An object becomes a new object ( new memory address reference count is 1 original object count unchanged

Release -1 if 0 free memory
autorelease object reference count -1 if 0 Not immediately released, recently pool release
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 options: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 to use attributes?
1.To make a member asPublic.
2. OutletGenerally declared as attributes(This memory is in the system control, but we should still do the same operation, the following will speak)
3.If many functions need to change this object , or This function is triggered 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];
}
}
AsssignCompared to the pointer assignment, do not operate the reference count, note that the original object is not necessary, be sure to set this toNil
RetainEquivalent to the reference count of the original object plus1
CopyDoes not change the reference count of the original object, generating a new object reference count of1
Attention:
Self.testobjectThe value of the lvalue is calledsettestobject method get method, get method Relatively simple needless to say Span class= "S1" >
true testobject use member variable
Self.testobject = [[Testobject alloc] init];// wrong Span class= "S1" > Reatin two times
Testobject = [Nsarray objectbyindex:0];// wrong unsafe, no retain back Release error
if testobject mem leak

automatically manage objects
IosProvides a lot ofStatic (+)class methods for creating objects, which are static and can be directly used with the class name
Calls such as:
NSString *teststring = [nsstring stringwithformat:@ "test"];
TestStringis 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.

5. Exceptions
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

IOS detailed memory management

Copy and theretainthe Difference
Copy: Create an index count of1object, and then releases the old object
Retain: Releases the old object, assigns the value of the old object to the input object, and then increases the index count of the input object to1
What the hell does that mean?
Copyretain not:
For example a nsstring0x1111@ "STR"
Copynsstring0x2222retain1< Span class= "S1", the old object does not change
Retainnsstring after the same address (set up a pointer, pointer copy), the content of course is the same, the object's retain value +1
that is, retain is a pointer copy, copy is a content copy. Wow, it's a lot easier than you think. ...

Strong and weak

settings for properties in IOS 5 new strong and weak keywords to decorate properties ( ARC not supported before iOS 5 )

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;

unsafe_unretained

Unsafe_unretained is the ios5 version of the assign , namely unsafe_unretained , weak, assign Three are all a kind. because ios5 use is weak , that in ios4.3 can not use, if you will weak change to unsafe_unretained , then it can be used. In the end , IOS 5 was used by a system that replaces weak with this attribute .  < /c9>

Copy: This thing is probably the most difficult thing for most people to figure out, and I don't understand it. Listen to other people say this thing basically no, the effect and retain is no different, the only difference is that copy is only used for NSString and not for nsmutablestring.  

However, as if a class inherits NSObject, the attributes in this class need to use copy, such as:

#import <Foundation/Foundation.h>

#import <MapKit/MKAnnotation.h>

@interface Annotation:nsobject <MKAnnotation> {

cllocationcoordinate2d coordinate;

NSString *title;

NSString *subtitle;

}

@property (nonatomic) cllocationcoordinate2d coordinate;

@property (nonatomic, copy) NSString *title;

@property (nonatomic, copy) NSString *subtitle;

@end

Anyway, it's going to be so much later.

property defaults to:readwrite,Assign, Atomic ( without this keyword

Use assign to decorate proxy properties under MRC , avoid circular references , use weak under ARC

Why agents use weak instead of assign:

I just ran into this problem and solved it. For ARC, the solution are to use the weak attribute instead of assign.

The crash come because the delegate

Have an assign attribute, and

has been deallocated.

Thus When you attempt the Respondstoselector method on delegate, you get a exc_bad_access. This is because objects, the Assign property would not have set to nil when they was deallocated. (Hence why doing a!self.delegate before the respondstoselector does isn't prevent the responsetoselector from being called On a deallocated object, and still crashes your code)

The solution is to use the weak attribute, and because when the object deallocates, the pointer would be set the nil. So when your code calls Respondstoselector on a nil, Objective C would ignore the call, and not crash.

As already mentioned, using a strong or assign attribute on a delegate (as many has mentioned) in ARC would result in a re Tain cycle. So don ' t does it, you don ' t need to.

3. http://blog.csdn.net/itianyi/article/details/9018567

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

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

Using copy: On NSString

Use retain: For other nsobject and its subclasses

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.

iOS strong, weak, assign, copy

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.