嘿 stackOverflow 社区。我正在阅读 Big Nerd Ranch 的 Objective C 书,并且遇到了有关定义和设置类的有趣章节(如果您熟悉的话,请参阅第 17 章)。其中的挑战是我们编写一个程序,在其中定义一个具有多个属性和实例变量的股票类。我已经能够让程序按照要求工作,但我想稍微修改一下,让它也 NSLog a stockName,这样我就可以看到哪些股票与其属性相关联。
基本上,有没有办法让这个 block 的代码更加简洁:
NSString *appleName = @"AppleInc";
[Apple setStockIdentifier:appleName];
也许更像这样:
[Apple setStockIdentifier:"AppleInc"];
我尝试在类文件中将属性设置为字符,但无法使其工作。我对此很陌生,但我认为为 stockIdentifier 值声明一个新的 NSString 是不需要的额外代码。任何反馈将不胜感激。
以下是我的主文件:
#import <Foundation/Foundation.h>
#import "StockHolding.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
StockHolding *Apple = [[StockHolding alloc] init];
NSString *appleName = @"AppleInc";
[Apple setStockIdentifier:appleName];
[Apple setPurchaseSharePrice:2.30];
[Apple setCurrentSharePrice:4.50];
[Apple setNumberOfShares:40];
StockHolding *HomeDepot = [[StockHolding alloc] init];
NSString *homeDepotName = @"Home Depot Inc";
[HomeDepot setStockIdentifier:homeDepotName];
[HomeDepot setPurchaseSharePrice:12.19];
[HomeDepot setCurrentSharePrice:10.56];
[HomeDepot setNumberOfShares:90];
StockHolding *Cisco = [[StockHolding alloc] init];
NSString *ciscoName = @"Cisco Inc";
[Cisco setStockIdentifier:ciscoName];
[Cisco setPurchaseSharePrice:45.10];
[Cisco setCurrentSharePrice:49.51];
[Cisco setNumberOfShares:210];
NSMutableArray *listOfStocks = [NSMutableArray arrayWithObjects:Apple, HomeDepot, Cisco, nil];
for (StockHolding *currentStock in listOfStocks) {
NSLog(@"%@, Purchase Share Price: %.2f; Current value: %.2f; Number of shares: %i",[currentStock stockIdentifier],[currentStock purchaseSharePrice], [currentStock currentSharePrice], [currentStock numberOfShares]);
}
}
return 0;
}
以下是StockHolding.h的内容:
#import <Foundation/Foundation.h>
@interface StockHolding : NSObject
{
//char stockIdentifier;
float purchaseSharePrice;
float currentSharePrice;
int numberOfShares;
}
@property NSString *stockIdentifier;
@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;
-(float) costInDollars; //purchaseSharePrice * numberOfShares;
-(float) valueInDollars; //currentSharePrice * numberOfShares;
@end
这里是 StockHolding.m:
#import "StockHolding.h"
@implementation StockHolding
@synthesize currentSharePrice, purchaseSharePrice, numberOfShares, stockIdentifier;
-(float)costInDollars;
{
return (purchaseSharePrice * numberOfShares);
}
-(float)valueInDollars;
{
return (currentSharePrice * numberOfShares);
}
@end
最佳答案
这只是一个语法错误。
[Apple setStockIdentifier:"AppleInc"];
应该是...
[Apple setStockIdentifier:@"AppleInc"];
关于objective-c - 设置记录数组数据时要调用的类标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24710079/