Ios strong and weak

Source: Internet
Author: User

I have added a new knowledge in iOS5, that is, ARC. In fact, I don't like it very much because I am used to managing the memory myself. However, learning is still necessary. During iOS development, attribute definitions are often related to retain, assign, and copy. I think everyone is familiar with them. I will not introduce them here. There are many related articles on the Internet. Now let's look at the New Keyword strong, weak, unsafe_unretained in iOS5. it can be similar to learning strong and retain corresponding to previous keywords. weak and unsafe_unretained functions are similar (a little different. We will introduce them later. These two new keywords are similar to assign ). With these new keywords in iOS5, you don't need to manually manage the memory. programmers who transfer from other languages such as java are very useful. The strong keyword is similar to retain. When it is used, the reference count is automatically + 1, and the instance is used to better describe everything. @ property (nonatomic, strong) NSString * string1; 2. @ property (nonatomic, strong) NSString * string2; there are two attributes: 1. @ synthesize string1; 2. @ synthesize string2; guess what results the following code will output? 1. self. string1 = @ "String 1"; 2. self. string2 = self. string1; 3. self. string1 = nil; 4. NSLog (@ "String 2 = % @", self. string2); the result is: String 2 = String 1 because string2 is a property defined by strong, reference count + 1 so that all the values they point to are @ "String 1 ", this is not difficult to understand if you are familiar with retain. Next let's look at the weak Keyword: If two attributes are declared as follows: 1. @ property (nonatomic, strong) NSString * string1; 2. @ property (nonatomic, weak) NSString * string2; and define 1. @ synthesize string1; 2. @ synthesize string2; Let's guess what the output below is? 1. self. string1 = [[NSString alloc] initwithuf8string: "string 1"]; 2. self. string2 = self. string1; 3. self. string1 = nil; 4. NSLog (@ "String 2 = % @", self. string2); the result is: String 2 = null. string1 and self. string2 points to the same address, and string2 does not have a retain memory address, while self. string1 = nil released the memory, so string1 is nil. The pointer declared as weak. Once the address pointed to by the pointer is released, these pointers will be assigned as nil. This benefit effectively prevents wild pointers. In the c/c ++ development process, why do Daniel say that when the pointer space is released, the pointer should be assigned NULL. here we use the weak keyword to help us with this step. Next let's look at unsafe_unretained. We can see from the name that unretained is unsafe. It is similar to weak because it is unretained, but it is unsafe. What is unsafe? Let's look at the instance below. If two attributes are declared as follows: 1. @ property (nonatomic, strong) NSString * string1; 2. @ property (nonatomic, unsafe_unretained) NSString * string2; then, Let's guess what the following code will return? 1. self. string1 = [[NSString alloc] initwithuf8string: "string 1"]; 2. self. string2 = self. string1; 3. self. string1 = nil; 4. NSLog (@ "String 2 = % @", self. string2); please note that I didn't tell you what output will happen here, because there will be no output at all, and your program will crash. What is the reason? It is actually caused by a wild pointer, so it is terrible. Why does it cause a wild pointer? Similar to the pointer declared by unsafe_unretained, string2 does not know it has been released because self. string1 = nil has released the memory, so it is a wild pointer. Then the access to the memory of the wild pointer causes crash. Therefore, use the unsafe_unretained keyword as little as possible. Strong, weak, and unsafe_unretained are often used to declare attributes. To declare a temporary variable, use _ strong, _ weak, _ unsafe_unretained, _ autoreleasing, its usage is similar to that described above. Let's look at the instance. 1. _ strong NSString * yourString = [[NSString alloc] initwithuf8string: "your string"]; 2. _ weak NSString * myString = yourString; 3. yourString = nil; 4. _ unsafe_unretained NSString * theirString = myString; 5. // now all the pointers are nil again: 1. _ strong NSString * yourString = [[NSString alloc] initwithuf8string: "string 1"]; 2. _ weak NSString * myString = yourString; 3. _ unsafe_unretained NSString * theirS Tring = myString; 4. yourString = nil; 5. // The pointers of yourString and myString are both nil, while theirString is not nil, but a wild pointer. Here we will also talk about string-related. If NSString * str = @ "str test"; in this way, a String constant will be declared, so that the Declaration is not subject to the aforementioned restrictions. Example: 1. _ strong NSString * yourString = @ "test string"; 2. _ weak NSString * myString = yourString; 3. yourString = nil; 4. // currently, myString still has a value NSString * str = [[NSString alloc] initWithString: @ "test"]; in this way, the return value is also a String constant, the effect is the same as NSString * str = @ "test. However, we have to follow Apple's memory management. In non-ARC scenarios, we still need to call release. In fact, there is no need to call or memory leakage. _ Autoreleasing usage: in c/c ++ and objective-c memory management, there is one rule: who allocates and releases. _ Autoreleasing can delay the object release. For example, if you want to upload an uninitialized object to a method and implement the object in this method, this situation will be when _ autoreleasing is performed. Example: 1. -(void) generateErrorInVariable :( _ autoreleasing NSError **) paramError {2. NSArray * objects = [[NSArray alloc] initWithObjects: @ "A simple error", nil]; 3. NSArray * keys = [[NSArray alloc] initWithObjects: NSLocalizedDescriptionKey, nil]; 4. NSDictionary * errorDictionary = [[NSDictionary alloc] initWithObjects: objects forKeys: keys]; 5. * paramError = [[NSError alloc] initWithDomain: @ "MyApp" Code: 1 userInfo: errorDictionary]; 6 .} 7. -(void) test 8. {9. NSError * error = nil; 10. [self generateErrorInVariable: & error]; 11. NSLog (@ "Error = % @", error); 12 .} after being translated by the compiler, it becomes: 1. -(void) test 2. {3. NSError * error = nil; 4. NSError * _ autoreleasing tmp = error; 5. [self generateErrorInVariable: & tmp]; 6. error = tmp; 7. NSLog (@ "Error = % @", error); 8 .} in this way, even the space applied inside the function can be used outside the function. It is also suitable for the principle of who allocates and who releases the space. The following code is also for a similar reason, but is applicable when ARC is not enabled: 1. -(NSString *) stringTest 2. {3. NSString * retStr = [NSString stringWithString: @ "test"]; 4. 5. return [[retStr retain] autorelease]; 6 .} after activating ARC, you should change it to: This method is feasible after testing, but it is not intended to write code like this, the example on the official website of _ autoreleasing is used to transmit reference parameters (like the NSError above ). So it is better not to use 1. -(NSString *) stringTest 2. {3. _ autoreleasing NSString * retStr = [NSString alloc] initWithString: @ "test"]; 4. 5. return retStr; 6 .} 1. -(NSString *) stringTest _ attribute _ (ns_returns_autoreleased) {NSString * retStr = [NSString alloc] initWithString: @ "test"]; return retStr ;} similar to the above functions. Returns an autorelease. Values: methord family. If the method name starts with alloc, init, copy, mutablecopy, and new, their return values are retain. The other values are returned by autorelease by default. The following is an example of the return value: 1. -(id) foo _ attribute (ns_returns_retained); // return value retain + 1, init, new, alloc, copy, mutablecopy default are this 2. -(id) foo _ attribute (ns_returns_not_retained); // return weak pointer reference, 3. -(id) foo _ attribute (ns_returns_autoreleased); // return autorlease, begin t default, there is a rule for Methods Starting with are this init, be sure to return id or parent class, subclass pointer, otherwise there must be warning. here is the original saying: www.2cto. cominit methods must be instance methods and must re Turn an Objective-C pointer type. additionally, a program is ill-formed if it declares or contains a call to an init method whose return type is neither id nor a pointer to a super-class or sub-class of the declaring class (if the method was declared on a class) or the static receiver type of the call (if it was declared on a protocol ). of course, you can also break this rule. If you declare the method as follows: 1. -(void) initStr _ attribute _ (objc _ Method_family (none); then it is correct.

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.