私はBigNerdRanchのObjective-Cのガイドに従っていますが、課題の1つ(第17章)で、彼はあなたが作成したオブジェクトの3つのインスタンスを作成するように求めています。私はクラスを作成し、セッターを実装しました。 、getterと2つのインスタンスメソッドを使用して、オブジェクトの3つのインスタンスを作成し、すべての変数を定義しました。次に、3つのオブジェクトを配列に入れ、forループで値を反復するように求められます。
私が抱えている問題は、「forループ」内でインスタンスメソッドを実行する方法がわからないことです。
これは私がこれまでに持っているものです(すべての値はランダムで架空のものです):
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
#import "StockHolding.h"
@implementation StockHolding
@synthesize purchaseSharePrice, currentSharePrice, numberOfShares;
- (float)costInDollars;
{
return purchaseSharePrice * numberOfShares;
}
- (float)valueInDollars;
{
return currentSharePrice * numberOfShares;
}
@end
main.m
#import <Foundation/Foundation.h>
#import "StockHolding.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
StockHolding *apple = [[StockHolding alloc] init];
[apple setPurchaseSharePrice: 10];
[apple setCurrentSharePrice: 50];
[apple setNumberOfShares: 20];
StockHolding *hmv = [[StockHolding alloc] init];
[hmv setPurchaseSharePrice: 15];
[hmv setCurrentSharePrice: 0];
[hmv setNumberOfShares: 17];
StockHolding *drpepper = [[StockHolding alloc] init];
[drpepper setPurchaseSharePrice: 5];
[drpepper setCurrentSharePrice: 15];
[drpepper setNumberOfShares: 70];
NSMutableArray *stocksList = [NSArray arrayWithObjects:apple, hmv, drpepper, nil];
for (NSObject z in stocksList) {
NSLog(@"Original cost: %@", [z costInDollars]);
NSLog(@"Current value: %@", [z valueInDollars]);
}
}
return 0;
}