iOS training------My C language notes, look forward to communicating with you!
The use and difference of copy,assign,strong,retain,weak,readonly,readwrite,nonatomic,atomic,unsafe_unretained
Recently in the process of learning iOS has encountered a lot of problems, know that the concept has seen the sample code, but it is not written or do not know how to use.
One of the most encountered times is when declaring a property, such as:
@property (? , ? ) ? *! ;
Yes, it is here, every time you encounter here, you do not know how to do, although it seems very simple (but it is really simple), but it is easy to confuse.
So today I will give you a summary, but also as their own later a memo, convenient for later inspection!
Note:These words are very important, is more than 99% of the company interview or written test must ask, so you understand!
Copy,assign,strong,retain,weak,readonly,nonatomic the difference, there is a need for friends to refer to the next.
This article is mainly from the meaning of these words and simple use, and then is the use of iOS development in the time of some differences, here is very important for the interview!
Meaning:
Copy the content (deep copy ), if the copy is called an array, copy the pointer ( shallow copy ), just copy the child element's pointer.
@property (nonatomic,copy) NSString *title;
@property (nonatomic, copy) Nsmutablearray *myarray;//not recommended
@property (nonatomic, copy) Someblocktype Someblock;
For underlying data types (nsinteger,cgfloat) and C data types (int, float, double, char, and so on)
@property (nonatomic, assign) int n;
@property (nonatomic, assign) BOOL IsOK;
@property (nonatomic, assign) CGFloat scalarfloat;
@property (nonatomic, assign) Cgpoint scalarstruct;
Equivalent to retain.
Strong inARCThe environment is the default property type.
@property (Nonatomic,readwrite,strong) NSString *title;
@property (Strong, nonatomic) Uiviewcontroller *viewcontroller;
@property (nonatomic, strong) ID childobject;
NSObject and its subclasses.
Release old value, retain new value.
Retain is a pointer copy (shallow copy) with a reference count plus 1 without causing the content to be copied .
@property (nonatomic, retain) Uicolor *mycolor;
Instead of the previous assign, the object is automatically set to nil after it is destroyed, preventing wild pointers.
Assign cannot be automatically set to nil and needs to be manually set to nil.
Delegate basically always uses weak to prevent circular references. The special case is that some of the methods that you want to call delegate in Dealloc are released, at this point if using weak will cause an exception, because it is nil at this time, then it is more appropriate to use assign.
@property (Weak, nonatomic) Iboutlet UIButton *mybutton;//at the top level iboutlet should be strong
@property (nonatomic, weak) ID parentobject;
@property (nonatomic,readwrite,weak) ID <MyDelegate> delegate;
@property (nonatomic, weak) nsobject <SomeDelegate> *delegate;
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.
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.
Unretained and unsafe, because it is unretained so and weak a bit similar, but it is unsafe.
@property(nonatomic,unsafe_unretained)Book *book1;
unsafe_unretainedID safeself = self;
Here are a few very important concepts:
- arc-Automatic Medical Technology
ARC is not garbage collection, but rather the compiler automatically inserts code to reduce programmer code input and errors.
It is also higher than garbage and efficiency, because it does not affect the running time, the equivalent of managing memory.
Always use properties to manage instance variables (except Init/dealloc) and to release all properties in Dealloc.
The code that frees the instance variable is automatically added to the dealloc, so there is no need to increase the code that frees the instance variable. No need to call [super Dealloc] Manually
Do not call Retain,release,autorelease, the compiler will automatically insert the relevant code.
Note The naming method, do not copyxxx the way you do not want to retain, the compiler will automatically retain based on the method name.
Do not have object pointers in C-language structures
IDs and void* can only be converted by bridging conversions
Instead of using NSAutoreleasePool, use @autoreleasepool{} blocks of code.
Convert arc Code:edit->refactor->convert to Objective-c arc
Retain cycle
Delegate and block are the main reasons for retain cycle
Remove Observer observers
Logout Notification Notification
Set non-weak delegate to nil cancel timer
Usage Differences:
A: Copy and retain:
1, copy is actually the establishment of a same object, and retain is not;
2, copy is a copy of the content, retain is a pointer copy;
3, copy is the content of the copy, for like NSString, it is true, but if copy is a Nsarray it? This is just a copy of the pointer to the corresponding element in the array. This is called "shallow copy".
4, copy of the situation: NSString *NEWPT = [pt copy];
At this time will re-open a memory on the heap 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 added 1 for NEWPT to manage 0x1122 this memory;
Two: Assign and retain:
1, assign: Simple assignment, do not change the index count;
2, assign situation: NSString *NEWPT = [ptassing]; At this point NEWPT and PT are exactly the same address is 0XAAAA content 0x1111 that is newpt is only the alias of PT, for any one operation is equal to another operation, Therefore Retaincount does not need to increase, 3, assign is the direct assignment value;
4, retain uses the reference count, retain causes the reference count plus 1,release to cause the reference count minus 1, when the reference count is 0 o'clock, the Dealloc function is called, the memory is recycled; 5, retain: nsstring *NEWPT = [ Ptretain]; 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 of "ABC", so the retaincount needs to be increased by 1;Three: readonly:ReadOnly: Produces only simple getter, no setter.
Four: ReadWrite:
ReadWrite: Simultaneous generation of Setter\getter methods Five nonatomic,atomic:
: 1, non-atomic access, the value of the property is not locked, multi-threaded concurrent access will improve performance. If this attribute is not added, the default is two access methods are atomic transaction access;
Weak and strong property (the difference between strong and weak references):
:2, The @property property of the member variable, the default is atomic, which provides multithreading security. atomic operations are necessary in a multithreaded environment, otherwise they may cause incorrect results
-
Atomic means setter/getter This function, which is a primitive operation. If more than one thread calls the setter at the same time, one thread does not run out of all the setter statements, and the other thread starts to perform the setter condition, which is equivalent to a lock on the end of the function, which guarantees the integrity of the data. Nonatomic does not guarantee the setter/getter of the original line, so you may be able to take something incomplete. Therefore, in multi-threaded environment atomic operation is very necessary, otherwise it may cause incorrect results.
For example, the setter function changes two member variables, if you use Nonatomic, getter may be taken to change only one of the variables when the state, so that the things can be a problem, is incomplete. Of course , if you do not need multi-threading support, with Nonatomic is enough, because it does not involve the operation of the lock, so it is relatively faster execution rate.
VI: weak and strong
- 1, weak and strong properties are only required when you open arc, and you cannot use retain release autorelease because ARC will do it for you automatically, but you need to use weak and strong on object properties , where strong is equivalent to the Retain attribute, and weak is equivalent to assign.
- 2, only one situation you need to use weak (the default is strong), is to avoid retaincycles (that is, the parent class contains the child class {parent class retain subclass}, the subclass called the parent class {subclass and retain the parent class}, which cannot be release)
- 3, the pointer is declared as weak, the pointer points to the address once released, these pointers will be assigned to nil. Such a benefit can effectively prevent the wild hands.
Seven: ARC (Automatic Reference counting):
1, the code is automatically added to the Retain/release, the original need to manually add the reference count to handle memory management of the code can be automatically completed by the compiler. This function is started in IOS 5/mac OS X 10.7 and can be used later with Xcode4.2.
Eight: Strong,weak,copy specific usage:
1. Specific point: Iboutlet can be weak,nsstring for copy,delegate General for the weak, others see the situation. In general, the properties of the class "internal" are set to strong, and the properties of the class "external" are set to weak. In the end it is a question of attribution. Be careful that circular references cause memory to fail to release.
2. You will see a lot of Retian without arc.
3. If you write @synthesize ABC = _ABC, then the system automatically helps you to declare a _ABC instance variable.
Using assign: for underlying data types (Nsinteger) and C data types (int, float, double,char, etc.)
Using copy: On NSString
Use retain: For other nsobject and its subclasses
Note: ********************
Assign: Default type, setter method directly assigns value without retain operation
Retain: Setter method to release the old value of the parameter , and then retain the new value.
Copy: Setter method for copy operation, same as retain
"Good Programmer's note sharing"--the use and difference of common keywords