Objective-c Properties Detailed

Source: Internet
Author: User



With regard to the property of Objective-c, many novice iOS developers will be confused, including experienced iOS development programmers,



Because Objective-c's property, say much, say less but also a lot, from MRR (Manual Retain Release) to Arc mode, many properties function similar



Names are not the same, such as Strony and retain, but also involved in release, Autorelease, Alloc, new,copy and other functions,



So I looked around and got lost in the multitude of property,



Today we specifically comb the keywords that support the propterty of Arc (IOS 5+):



Strong, weak, copy, Readonly/readwrite, Atomic/nonatomic,assign,retain






Because strong and retain function the same, so in the final summary, the comparison of all these keywords similarities and differences





1: Define a property



As below, we define a car's interface, which has a property of brand


 
// Car.h
#import <Foundation/Foundation.h>

@interface Car : NSObject

@property NSString *brand;

@end
//  Car.m

#import "Car.h"

@implementation car

@synthesize brand = _brand;

@end





2: Getter and Setter methods for attributes and synthesize



The compiler will generate getter and setter methods by default for properties


-(NSString *) brand
{
     return _brand; // _ brand even if the property name is specified by synthesize
}

-(void) setBrand: (NSString *) brand
{
     _brand = brand;
}





Note: Synthesize does not have to be explicitly declared unless the getter and setter methods of the properties are manually



Otherwise, the default generated code for Complier is the following format


@synthesize brand = _brand





The default method for the Synthesize keyword is to declare the instance of the brand attribute as _brand, which is _ + PropertyName



Of course you can specify for example brand = Xxxbrand






The compiler defaults to the same name as the Getter method and property, and the setter method is the Set+ property (capitalized), such as Setbrand



You can specify getter and setter method names for properties


@property (Nonatomic,getter=getbrand, setter = Setbrand:) nsstring *brand;





3:readonly and ReadWrite



Declaring the ReadOnly property


@property (readonly, Getter=getbrand) NSString *brand;





Declare the properties of ReadOnly, there must be no setter method, so you can use getter or dot method to get the value of the property, but must not be used



Setter Method Modification


Car *c = [[Car alloc]init];0
    
[c setBrand:@"tony"]; //Error
        
NSLog(@"%@", [c getBrand]);





Declared as ReadOnly does not mean that we can not modify, Propery's accessor method is provided to other interface calls,



In our interior, we are directly manipulating _brand instances, as follows


// Car.h
- (void)setBrand:(NSString *)brand;
 

// Car.m
- (void )setBrand:(NSString *)brand;
{
    _brand = brand;
}





readonly corresponding ReadWrite attribute, ReadWrite is the default behavior, can not display the declaration


@property (ReadWrite) NSString *brand;





4:atomic, Nonatomic



Atomic Atomic, default behavior, supports multi-threaded operation at the cost of greater than nonatomic



If you declare a property that is not running in a multithreaded environment, you can declare it as nonatomic directly


@property (nonatomic) NSString *brand;





Memory management






The OJECTIVE-C memory model, whether MRR or arc, determines whether an object is recycled based on the object's reference count



When an object has a reference count of 0, it is recycled (not necessarily immediately)












Starting from the principle of reference counting, Objective-c proposes three related properties



Strong, weak, copy






1:strony Property



The strong property, which declares that an object has another object, reference count + 1



An Instance object B of the strong property is added to the A object, and B is not freed until the A object is released.



Look at the following sample code



Declares a class Person,person has a property name


 
 
//
//  Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic) NSString *name;

@end
//  Person.m
#import "Person.h"

@implementation Person

- (NSString *)description
{ 
    return self.name;
}
@end





Declare a car class with two properties model and driver


 
 
//  Car.h


#import <Foundation/Foundation.h>
#import "Person.h"

@interface Car : NSObject

@property (nonatomic) NSString *model;
@property (nonatomic,strong) Person *driver;

@end





Main.m


 
// main.m
#import <Foundation/Foundation.h>
#import "Car.h"
#import "Person.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Person *john = [[Person alloc] init];
        john.name = @"John";
        
        Car *honda = [[Car alloc] init];
        honda.model = @"Honda Civic";
        honda.driver = john;
        
        NSLog(@"%@ is driving the %@", honda.driver, honda.model);
    }
    return 0;
}


As you can see, the Hoda object is responsible for the driver object






2:weak Property






The strong property, which is intuitive to display the direct relationship of the object, but also easily causes a memory leak,



Look at the following code, we slightly changed the Person.h, added the car property,


 
// Person.h
#import <Foundation/Foundation.h>

@class Car;

@interface Person : NSObject

@property (nonatomic) NSString *name;
@property (nonatomic, strong) Car *car;

@end





Then in MAIN.M



Add a row






John.car = Honda;






At this point, John and Hoda hold each other












The two, which form the retain cycle (the one that holds each other), is a case of a typical memory leak.






If car is declared as weak, the problem is solved



@property (nonatomic, weak) Car *car;















3:copy Property



Copy differs from strong and does not have a copy object, but instead copies the object (must conformNSCopyingprotocol)






Sample code


 
#import <Foundation/Foundation.h>
#import "Car.h"
#import "Person.h"


int main(int argc, char *argv[])
{
    
    
    Car *bmw = [[Car alloc]init];
    
    Person *driver = [[Person alloc]init];
    
    NSMutableString *name = [NSMutableString stringWithFormat:@"zhangsan"];//mutable 的name 为zhangsan
    
    [driver setName:name];
    [name setString:@"lisi"];//修改为lisi
    [driver setCar:bmw];
    
    [bmw setModel:@"X5"];
    [bmw setDriver:driver];
    
    NSLog(@"%@", [driver name]);//仍然是zhangsan

}


The Copy property is copied when the value is assigned, so even if the value is mutable, the value of the property is not modified.






Now for strong holders, copy is particularly well-suited for simply storing properties that are worth






These are the properties that arc supports.



4: attribute retain



Equivalent to Strong









5:unsafe_unretained



similar to weak, unlike weak. If the weak property points to an object that is destroyed, the weak property is set to nil,



And unsafe_unretained does not, then may form the problem of dangling pointers






6:assign



Default properties, no need to display declarations



Specifies the setter method for simple assignment to the underlying data type (nsinteger,cgfloat)



and C data types (int, float, double, char), and so on.






Summary:



Atomic//default



Nonatomic






Strong=retain//default



Weak



Assign//default



unsafe_unretained



Copy






ReadOnly



ReadWrite//default








Reference:



Http://rypress.com/tutorials/objective-c/properties



Http://rypress.com/tutorials/objective-c/memory-management



Http://stackoverflow.com/questions/8927727/objective-c-arc-strong-vs-retain-and-weak-vs-assign



Objective-c Properties Detailed


Related Article

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.