Objective-C study note _ attributes

Source: Internet
Author: User

Objective-C study note _ attributes
I. Attributes

The property is defined by Objective-C 2.0 and provides default Implementation of the setter and getter methods for instance variables. It can simplify the program code to a certain extent and enhance the access security of instance variables.

Attribute Declaration

Similar to a class, attributes also need to be declared and implemented.

Attribute Declaration: Use @ property to declare the attribute

For example:@property NSString *name;

Equivalent to two methods (setter and getter) defined in @ interface ):

- (void)setName:(NSString *)name;- (NSString *)name;
Attribute implementation

Attribute implementation: Use @ synthesize to implement the attribute

For example:@synthesize name = _name;

Equivalent to @ implementation, which implements setter and getter

- (void)setName:(NSString *)name{    _name = name;}- (NSString *)name{    return _name;}

Note:

The original @ property declaration is combined with another declaration @ synthesize in the implementation file to create the setter and getter methods. After Xcode4.5 @ synthesize will be automatically generated internally, without manual addition. However,If you want to override the setter and getter methods in the. m implementation file after the attribute @ property declaration, you must add @ synthesize to the. m implementation file.

After the attribute declaration, rewrite the setter and getter methods and declare @ synthesize as follows:

# Import
  
   
@ Interface Person: NSObject @ property NSString * name;-(void) setName :( NSString *) name;-(NSString *) name; @ end # import Person. h @ implementation Person/* after attribute declaration, the setter and getter methods must be rewritten. @ synthesize */@ synthesize name = _ name;-(void) setName :( NSString *) must be declared *) name {_ name = name;}-(NSString *) name {return _ name;} @ end
  
2. Attribute)

Objective-C provides attributes to simplify programmer coding,Which of the following keywords are provided for the attribute? To control the implementation details of setter and getterThese keywords are called attributes ). There are three categories of attributes.

Class 1: read/write control (readonly, readwrite, setter, getter)

readonlyTells the compiler to declare only the getter method (without the setter method ).

For example:@ Property (readonly) NSString * name; // equivalent to-(NSString *) name;

readwrite, Telling the compiler to declare both setter? Declare getter.

For example:@ Property (readwrite) NSString * name; // equivalent to-(NSString *) name;-(void) setName :( NSString *) name;The default settings for read/write control.

Setter = method nameSpecifies the method name of the setter.

Getter = method nameSpecifies the method name of the accessor.

Class 2: atomic control (nonatomic, atomic)

atomic, The setter and getter methods are absolutely secure in multi-thread access, that is, the setter and getter internal multi-thread access processing. Original? The default settings of child control are atomic.

nonatomic, The setter and getter methods do not implement multi-thread access processing internally, just common setter and getter? Method.

Setter and getter are used everywhere during program development.Atomic, RequiredLocks and locks the setter and getter to ensure thread access security.YesIt occupies system resources and reduces system performance..Usually set to nonatomicSome attributes are defined as atomic only when thread security is required.

For example:

@ Property (readwrite, nonatomic) NSString * name; // equivalent to-(NSString *) name;-(void) setName :( NSString *) name;
Category 3: semantic settings (assign, retain, and copy)

assign, Setter, getter internal implementation is direct value assignment, applicable to basic data types, default value.

For example:

@property (nonatomic, assign) NSString *name;- (void)setName:(NSString *)name{  _name = name;}- (NSString *)name{  return _name;}

retainThe internal implementation of setter and getter will optimize the memory and apply to the object type.

For example:

@property (nonatomic, retain) NSString *name;- (void)setName:(NSString *)name{if(_name != name){  [_name release];  _name = [name retain];}}- (NSString *)name{  return [[_name retain]autorelease];}

copyThe internal implementation of setter and getter will also optimize the memory and copy a copy. This applies to special object types and is generally applicable to NSSting.

For example:

@property (nonatomic, copy) NSString *name;- (void)setName:(NSString *)name{if(_name != name){  [_name release];  _name = [name copy];  }}- (NSString *)name{  return [[_name retain]autorelease];}

Summary:

If the attribute is? Use assign to set the semantics of object types (such as int and float) attributes. If the property is of the object type (? Such as NSStrng and NSArray. If the property is of the object type and you want to get the copy parameter, use the copy keyword. Iii. Point syntax

Point syntax is the syntax format defined in Objective-C 2.0. Provided? Convenient attribute access? .

Usage of point syntax

Point syntax can be used for all methods that conform to the system's default setter and getter writing formats.

For example:[person1 setName:@”ZhangSan”];Can be equivalentperson1.name = @”ZhangSan”;.

NSString *name = [person1 name];Can be equivalentNSString *name = person1.name;

The property is a pair of getter and setter methods, and the dot syntax is another calling format of the property.

Iv. KVC

KVC (Key-Value-Coding), Key-Value EncodingIsIndirect access to instance variables.

Key: key used to identify instance variables.

Vlaue: The value corresponding to the instance variable.

Modify Value

SetValue: forKey: setValue: forKeyPath: setValue: forUndefinedKey: setValuesForKeysWithDictionary:

Get value

ValueForKey: valueForKeyPath: valueForUndefinedKey:

Notes

If the key does not exist, setValue: forUndefinedKey:

The system throws an exception by default.

To better experience the use of KVC, the following is the sample code:

Requirements
Defines a Classroom class: instance variable: Classroom number, student (Person class)
The setter and getter methods are not specified for instance variables.

The Classroom. h file code is as follows:

# Import
  
   
@ Class Person; @ interface Classroom: NSObject {@ protected NSString * _ classNum; Person * _ student;} # pragma mark-Override parent class method-(void) setValue :( id) value forUndefinedKey :( NSString *) key;-(id) valueForUndefinedKey :( NSString *) key; @ end
  

The Classroom. m file code is as follows:

# Import Classroom. h # import Person. h @ implementation Classroom-(void) setValue :( id) value forUndefinedKey :( NSString *) key {NSLog (@ no such instance variable: % @, key);}-(id) valueForUndefinedKey :( NSString *) key {NSLog (@ does not have this instance variable: % @, key); return nil ;}@ end

The Person. h file code is as follows:

# Import
  
   
@ Interface Person: NSObject/* instance variable */{@ protected NSString * _ name; NSInteger _ age ;}# pragma mark-attribute Declaration/* code specification: the property name does not include _ *. The property contains three parts: instance variables, the setter method of instance variables, and the getter method of instance variables */@ property NSString * holobby; @ property NSString * sex; # pragma mark-attribute (feature)/* first type attribute: read/write control * readonly: equivalent to providing only the getter Method * readwrite: it is equivalent to providing the setter and getter Methods * default: readwrite * General settings: readwrite * // @ property (readonly) NSString * name;/* Second Class: attribute: atomicity control * atomic: atomicity * nonatomic: Non-atomicity * default: atomic * General settings: nonatomic */@ property (readwrite, nonatomic) NSString * height; /* Category 3 attribute: semantic setting * assign: Non-object type use: int, float, NSInteger * retain: Object Type use: NSString, NSArray, will be set to setter, getter Method Memory Optimization * copy: Object Type usage, memory optimization for setter and getter Methods * default: assign */@ property (readwrite, nonatomic, assign) NSInteger weight; @ property (readwrite, nonatomic, retain) NSString * marry; @ property (readwrite, nonatomic, copy) NSString * work;/* common attribute Declaration */@ property (nonatomic, retain) NSString * blood; # pragma mark-/* instance variable setter, getter Method */-(void) setName :( NSString *) name;-(NSString *) name; -(void) setAge :( NSInteger) age;-(NSInteger) age; @ end
  

The Person. m file code is as follows:

# Import Person. h @ implementation Person # pragma mark-attribute implementation/* is equivalent to implementing the setter and getter Methods * can omit @ synthesize row */@ synthesize holobby = _ holobby; @ synthesize sex = _ sex;-(void) setName :( NSString *) name {_ name = name;}-(NSString *) name {return _ name;}-(void) setAge :( NSInteger) age {_ age = age;}-(NSInteger) age {return _ age;} @ end

The main. m file code is as follows:

# Import
  
   
# Import Person. h # import Classroom. hint main (int argc, const char * argv []) {@ autoreleasepool {/* defines a Classroom class: instance variable: Classroom number, student (Person class) * If the instance variable is not set to setter, The getter Method * // * creates a Person object and a Classroom object */Person * stu = [[Person alloc] init]; classroom * classroomOne = [[Classroom alloc] init];/* assign values using KVC */[classroomOne setValue: @ 5211 forKey: @ _ classNum]; [classroomOne setValue: stu forKey: @ _ student]; [classroomOne setValue: @ 5212 forKey: @ classroomNum]; [classroomOne setValue: @ dd forUndefinedKey: @ sss]; [classroomOne setValue: @ ZhangSan forKeyPath: @ _ student. name];/* use KVC values */NSLog (@ classNum: % @, [classroomOne valueForKey: @ _ classNum]); NSLog (@ student name: % @, [classroomOne valueForKeyPath: @ _ student. name]); NSLog (@ student name: % @, [classroomOne valueForKeyPath: @ _ student002]);} return 0 ;}
  
 

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.