1set,get使用
創建BNRStockHolding類
頭文件聲明如下
#import <Foundation/Foundation.h>
@interface BNRStockHolding : NSObject
{
CGFloat _purchaseSharePrice;
CGFloat _currentSharePrice;
NSInteger _numberOfShares;
}
- (void)setPurchaseSharePrice:(CGFloat)purchaseSharePrice;
- (void)setCurrentSharePrice:(CGFloat)currentSharePrice;
- (void)setNumberOfShares:(NSInteger)numberOfShares;
- (CGFloat)purchaseSharePrice;
- (CGFloat)currentSharePrice;
- (NSInteger)numberOfShares;
- (CGFloat)costInDollars;
- (CGFloat)valueInDollars;
- (void)setMessage:(CGFloat)p current:(CGFloat)c number:(NSInteger)n;
- (void)showMessage;
@end
實現如下:
#import "BNRStockHolding.h"
@implementation BNRStockHolding
- (void)setPurchaseSharePrice:(CGFloat)purchaseSharePrice{
_purchaseSharePrice=purchaseSharePrice;
}
- (void)setCurrentSharePrice:(CGFloat)currentSharePrice{
_currentSharePrice=currentSharePrice;
}
- (void)setNumberOfShares:(NSInteger)numberOfShares{
_numberOfShares=numberOfShares;
}
- (CGFloat)purchaseSharePrice{
return _purchaseSharePrice;
}
- (CGFloat)currentSharePrice{
return _currentSharePrice;
}
- (NSInteger)numberOfShares{
return _numberOfShares;
}
- (CGFloat)costInDollars
{
return _purchaseSharePrice*_numberOfShares;
}
- (CGFloat)valueInDollars
{
return _currentSharePrice*_numberOfShares;
}
- (void)setMessage:(CGFloat)p current:(CGFloat)c number:(NSInteger)n{
[self setPurchaseSharePrice:p];
[self setCurrentSharePrice:c];
[self setNumberOfShares:n];
}
- (void)showMessage{
NSLog(@"purchasePrice is %lf",[self purchaseSharePrice]);
NSLog(@"currentPrice is %lf",[self currentSharePrice]);
NSLog(@"numberOfShares is %ld",[self numberOfShares]);
NSLog(@"costInDollars is %lf",[self costInDollars]);
NSLog(@"valueInDollars is %lf",[self valueInDollars]);
}
@end
主函數測試如下:
#import <Foundation/Foundation.h>
#import"BNRStockHolding.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
BNRStockHolding *s1=[[BNRStockHolding alloc] init];
BNRStockHolding *s2=[[BNRStockHolding alloc] init];
BNRStockHolding *s3=[[BNRStockHolding alloc] init];
[s1 setMessage:2.30 current:4.50 number:40];
[s2 setMessage:12.19 current:10.56 number:90];
[s3 setMessage:45.10 current:49.51 number:210];
NSMutableArray *data=[NSMutableArray array];
[data addObject:s1];
[data addObject:s2];
[data addObject:s3];
for(BNRStockHolding *s in data)
{
[s showMessage];
}
}
return 0;
}
2屬性的使用
創建一個BNRPerson類
頭文件聲明如下
bmi實現如下
主函數測試操作如下,用set、get方法也可,用點方法也可。
3可變數組練習
main.m文件
4類的繼承練習
創建BNRPerson類
頭文件如下
實現如下:
派生類BNREmployee 繼承BNRPerson
.h文件聲明如下:
實現如下:
對父類的BMI方法進行了重寫
main.m測試如下
5description和dealloc練習
用%@輸出對象信息時,處理%@時程序會先向對象發送description消息,默認以字符串形式返回內存地址。
類的實例被釋放時將執行dealloc方法。
通過重寫dealloc方法和description方法可以監測
定義一個BNRAsset類
頭文件,實現,測試main.m如下
系統調用dealloc方法,輸出了deallocating +重寫的description方法返回的字符串信息。這樣我們就知道了什麼時間 哪個實例被釋放了。