我在使用類時遇到了問題。我必須創建NSObject的子類的「StockHolding」對象。我創建實例變量和方法。然後我創建了3個完整的名稱和價格的庫存代碼,並將它們加載到一個可變數組中。我無法快速枚舉數組中的對象並打印每個對象的屬性(價格)。問題是我試圖通過對象枚舉並打印屬性時出現錯誤。我嘗試了幾種不同的方法來解決問題,但沒有運氣。有任何想法嗎?我還注意到當前的庫存不是打印一個名字,而是一個指針位置。也許這些問題是相關的。提前致謝。大書呆子牧場目標C第17章挑戰 - 定義類
'頭'
#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(NSObject *'try' for(StockHolding *')如果你的對象是正確的類類型,你將得到自動完成。這實際上是對象的子類化的目的是去公共超級,而不是去直接給NSObject這是每個類超類 –
檢查響應標記給出,因爲它在一個答案中呈現相同的場景 –