The overall declaration and implementation of setter and getter methods can be replaced with @property later, but in the later iOS development, the setter method or Getter method is used alone in a relatively high frequency, the application is more extensive!
@Interface Person:nsobject
{
NSString *_name;
int _age;
Sex _sex; Enum Type here, which is a basic data type without adding "*"
float _height;
}
@end
The setter method is the method of assigning a value to a property.
Writing format:
1, in the declaration of the class:-(void) + (set+ attribute minus "_", the first letter capitalized): (Data Type/object/Class) + (attribute minus "_");
Precautions:
(1) Setter method must be object method
(2) There must be no return value
(3) must start with set, and set followed by the name of the member variable to be set to remove the underscore, and the first letter uppercase
(4) There must be parameters, the parameter type must be the same as the type of the member variable that needs to be set, and the parameter name is the name of the member variable to remove the underscore
Example:
-(void) SetName: (NSString *) name;
-(void) Setage: (int) age;
-(void) Setsex: (Sex) sex;
-(void) SetHeight: (float) height;
2, in the implementation of the class: curly braces can add other content, but must implement the property = (Remove the "_" property)
-(void) SetName: (NSString *) name{
_name = name;
}
-(void) Setsex: (Sex) sex{
_sex = sex;
}
Second, getter method is to get the member variable worth method
Writing format:
1. Declaration of class:-(data Type/object/Class) + (attribute minus "_")
Precautions:
(1) Getter method must be object method
(2) There must be a return value, and the return value must be the same as the type of the obtained member variable
(3) The method name is the name of the obtained member variable minus the underscore
(4) There must be no parameters
Example:
-(NSString *) name;
-(int) age;
-(sex) sex;
-(float) height;
2, the implementation of the class: in the implementation of the class can add other content, but must have a return + property
-(NSString *) name{
return _name;
}
-(Sex) sex{
return _sex;
}
Other applications:
1, a property can only getter method, there is no setter method, this property we call the read-only property
2, a property can also only setter method, there is no Getter method, this property we call write-only property
3, if there is both setter method and getter method, then this attribute we call the readable writable property
4, a property can also have no getter and setter, this property we call private property
5, the setter method and the getter method declaration and implementation can be directly replaced by the following (written in the declaration of the Class)
@property (nonatomic,assin) nsstring * name;
@property (nonatomic,assin) Sex sex;
OC Basics (iv) Setter and Getter methods