我在上课时遇到问题。我必须创建作为 NSObject 子类的“StockHolding”对象。我创建实例变量和方法。然后我创建了 3 个包含名称和价格的库存迭代,并将它们加载到一个可变数组中。我很难快速枚举数组中的对象并打印每个对象的属性(价格)。问题是我在尝试枚举对象并打印属性时遇到错误。我尝试了几种不同的方法来解决这个问题,但没有运气。有任何想法吗?我还注意到 currentStock 不是打印名称,而是打印指针位置。也许这些问题是相关的。提前致谢。
'标题'
#import <Foundation/Foundation.h>
@interface StockHolding : NSObject
{
float fPurchaseSharePrice;
float fCurrentSharePrice;
int iNumberOfShares;
}
@property float fPurchaseSharePrice;
@property float fCurrentSharePrice;
@property int iNumberOfShares;
-(float) fCostInDollars; //fPurchaseSharePrice * fNumberOfShares
-(float) fValueInDollars; //fCurrentSharePrice * fNumberOfShares
@end
'执行'
#import "StockHolding.h"
@implementation StockHolding
@synthesize fCurrentSharePrice, fPurchaseSharePrice, iNumberOfShares;
-(float)fCostInDollars; //fPurchaseSharePrice * iNumberOfShares
{
return (fPurchaseSharePrice * iNumberOfShares);
}
-(float)fValueInDollars; //fCurrentSharePrice * iNumberOfShares
{
return (fCurrentSharePrice * iNumberOfShares);
}
@end
'主要的'
int main(int argc, const char * argv[])
{
@autoreleasepool {
StockHolding *Apple = [[StockHolding alloc] init];
[Apple setFPurchaseSharePrice:225];
[Apple setFCurrentSharePrice:300];
[Apple setINumberOfShares:50];
StockHolding *Cisco = [[StockHolding alloc] init];
[Cisco setFPurchaseSharePrice:100];
[Cisco setFCurrentSharePrice:50];
[Cisco setINumberOfShares:75];
StockHolding *WalMart = [[StockHolding alloc] init];
[WalMart setFPurchaseSharePrice:75];
[WalMart setFCurrentSharePrice:150];
[WalMart setINumberOfShares:75];
NSMutableArray *Portfolio = [NSArray arrayWithObjects: Apple, Cisco, WalMart, nil];
for (NSObject *currentStock in Portfolio){
NSLog(@"Purchase Price: %@", currentStock );
NSLog(@"Details: %f", [currentStock FPurchaseSharePrice]); // <---Error is on this line. It says "No visible @interface for NSObject declares the selector fPurchaseSharePrice"
}
}
return 0;
}