例如;
下面的介面區段,使用@property指令識別屬性,宣告兩個setter以及getter方法,分別為numberOne、numberTwo。另外,宣告一個整數變數numberThree。在做這樣的宣告時,編譯器會另外產生兩個整數變數_numberOne、_numberTwo。
#import <Foundation/Foundation.h>
@interface Number : NSObject
{
int numberThree;
}
@property int numberOne, numberTwo;
- (void)printNumber;
- (void)setNumberThree:(int)number;
@end
在下面的實作區段中,實作了在介面區段中的兩個方法,分別為setNumberThree以及printNumber。在printNumber中,使用了getter方法self.numberOne以及self.numberTwo。如果不用點運算子(﹒),也可以使用實體方法,即[self numberOne]以及[self numberTwo]表示。我們也把編譯器產生的兩個整數變數_numberOne、_numberTwo的值印出來看看結果。setNumberThree是我們為整數變數numberThree產生的setter方法
#import "Number.h"
@implementation Number
- (void)setNumberThree:(int)number
{
numberThree = number;
}
- (void)printNumber
{
NSLog(@"numberOne = %d, numberTwo = %d, numberThree = %d, _numberOne = %d, _numberTwo = %d", self.numberOne, self.numberTwo, numberThree, _numberOne, _numberTwo);
}
@end
在下面的主程式中,使用編譯器產生的setter方法為變數_numberOne, _numberTwo設定整數值,分別為3與5。setter方法也可以用點運算子(﹒)表示,即cal.numberOne = 3、cal.numberTwo = 5。
#import <Foundation/Foundation.h>
#import "Number.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
Number *cal = [[Number alloc]init];
[cal setNumberOne:3];
[cal setNumberTwo:5];
[cal setNumberThree:10];
[cal printNumber];
}
return 0;
}
主控台輸出的結果如下;
2014-03-20 15:19:51.049 Calculation[1261:303] numberOne = 3, numberTwo = 5, numberThree = 10, _numberOne = 3, _numberTwo = 5
Program ended with exit code: 0
沒有留言:
張貼留言