我在上课时遇到了麻烦。我必须创建“StockHolding”对象,它们是NSObject的子类。我创建实例变量和方法。然后我创建了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;
}
答案 0 :(得分:2)
而是为你的for循环执行此操作
for (StockHolding *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"
}
答案 1 :(得分:0)
在您的NSLog中:FPurchaseSharePrice
应为fPurchaseSharePrice
。
此外,如果覆盖 - (NSString *)描述,打印对象将产生该字符串,而不是您当前看到的该对象的指针。
- (NSString *)description
{
return [NSString stringWithFormat:@"StockHolding: %.2f, %.2f", self.fCostInDollars, self.fValueInDollars];
}
收率:
Purchase Price: StockHolding: 11250.00, 15000.00
而不是:
Purchase Price: <StockHolding: 0x7fe438c0a480>
最后,您可以执行以下操作:
,而不是在for循环中转换为NSObject
for (StockHolding *currentStock in Portfolio)
可能没有回应的错误会消失。
答案 2 :(得分:0)
好吧,就像它说:你没有一个有这个名字的方法。在Objective-C中,方法名称区分大小写,并且您将属性(和相应的访问者)声明为fPurchaseSharePrice
。你想用这个:
NSLog(@"Details: %f", [currentStock fPurchaseSharePrice]);