First, write a simple Get,set method to familiarize yourself with its role.
//Fraction.h@interfaceFraction:nsobject-(void) Setnumber: (int) n;-(int) GetNumber;//fraction.m#importFraction.h@implementationfraction{intNumber ;}-(void) Setnumber: (int) n; { number=N;}-(int) getnumber{returnNumber ; }
The above example is not difficult to see, set, get is actually two functions: the Set method has no return value, there is a parameter, the Get method has a return value, no parameters, its return value is the set method received in the parameter. Therefore, the set method and the Get method are collectively referred to as the Access method. There is a synthetic access method: @property.
First, the name of the attribute defined by @property should be the same as the instance variable, although this is not required. @property defined in the H file, you can simplify the get and set functions above as follows:
// Fraction.h @interface int number ; @end
In the implementation file, there is actually a synthesize function:
// fraction.m #import fraction.h@implemention Fraction @synthesize number;
Synthesize tells the OC compiler to generate a pair of set-valued and value methods for the number attribute. Here's the problem: I use the Set method and the Get method to set the value of the value directly in the main function using the [] Call method is OK, then the property is how to set the value of the value?
In the previous method, to get the value of number stored in Myfraction (object name), the following statement should be used
Main.m
Fraction *myfraction = [[Fraction alloc]init];
[Myfraction number];
This operation actually sends the number message to the Myfraction object, returning the desired value, and after having the property, you can write the following equivalent expression by using the dot operator
// main.m Fraction myfraction =3;
In other words, point syntax is actually a special method of calling a function. Note that you can also call point syntax for a custom method: for example, if you have a value method defined as numerator, you can use Myfraction.numerator in your program, although numerator is not defined as a property. However, the point operator is usually used on a property to set or get the value of an instance variable. Calls to other methods are usually invoked using the [] syntax.
Finally, it is necessary to add that the @synthesize in the implementation file can be omitted, and if omitted, the compiler will name the underlying instance variable as _number, respectively.
---restore content ends---
About get, set methods, and the use of point syntax