Objective-C 编码实践:自写类和枚举方式输出新建类的各个成员

来源:互联网 发布:sql server分离mdf 编辑:程序博客网 时间:2024/05/16 20:31
StockHolding.h
#import <Foundation/Foundation.h>@interface StockHolding : NSObject{    float purchaseSharePrice;    float currentSharePrice;    int numberOfShares;}@property float purchaseSharePrice;@property float currentSharePrice;@property int numberOfShares;-(float)costInDollars;-(float)valueInDollars;@end


StockHolding.m

这里有个很神奇的事情就是自动生成get、set方法的变量引用时,需要"_"开头

#import "StockHolding.h"@implementation StockHolding-(float)costInDollars{    float cost =  _purchaseSharePrice * _numberOfShares;    return cost;}-(float)valueInDollars{    return _currentSharePrice * _numberOfShares;}@end

main.m

一定不要误用关键字

#import <Foundation/Foundation.h>#import "StockHolding.h"int main(int argc, const char * argv[]){    @autoreleasepool {                StockHolding *StockHonding1 = [[StockHolding alloc] init];        [StockHonding1 setNumberOfShares:40];        [StockHonding1 setPurchaseSharePrice:2.30];        [StockHonding1 setCurrentSharePrice:4.50];                StockHolding *StockHonding2 = [[StockHolding alloc] init];        [StockHonding2 setNumberOfShares:40];        [StockHonding2 setPurchaseSharePrice:2.30];        [StockHonding2 setCurrentSharePrice:4.50];                StockHolding *StockHonding3 = [[StockHolding alloc] init];        [StockHonding3 setNumberOfShares:40];        [StockHonding3 setPurchaseSharePrice:2.30];        [StockHonding3 setCurrentSharePrice:4.50];                NSMutableArray *dataList = [NSMutableArray array];                [dataList addObject:StockHonding1];        [dataList addObject:StockHonding2];        [dataList addObject:StockHonding3];                for(StockHolding *s in dataList){                        NSLog(@"the StockHolding number is %d",[s numberOfShares]);            NSLog(@"the StockHolding purchase shares price is %.2f",[s purchaseSharePrice]);            NSLog(@"the StockHolding current share Price is %.2f",[s currentSharePrice]);            NSLog(@"the StockHolding cost in dollars is %.2f",[s costInDollars]);            NSLog(@"the StockHolding value in dollars is %.2f",[s valueInDollars]);        }                NSLog(@"Hello, World!");//        NSArry *dataList = [Stock]    }    return 0;}


0 0
原创粉丝点击