我在上课时遇到麻烦。我必须创建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;
}

最佳答案

而是为您的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"
}

关于objective-c - 大 Nerd 牧场 objective-c 第17章挑战-定义类(class),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12149653/

10-09 04:20