【发布时间】:2015-07-29 20:31:24
【问题描述】:
我是一名 Objective-C 菜鸟,正在学习教程,但遇到了一个奇怪的问题,我想更好地理解。
我正在循环制作一个股票对象组合,这些对象有 50/50 的机会成为“foreignStock”或只是“股票”——不同之处在于转换率属性。对象 stock 是一个超类,foreignStock 是 stock 的子类。
我想创建一个指针,掷硬币来决定它是哪种类型,然后分配我需要的值。既然子类和超类都有currentSharePrice之类的东西,为什么我不能在抛硬币后设置它们呢?
这是我的 main.m 供审查:
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Declare portfolio and set the conversion rate
BNRPortfolio *mikesPortfolio = [[BNRPortfolio alloc] init];
NSUInteger globalConRate = 1.2;
// Array of ticker names - remove them as they are used
NSMutableArray *tickerNames = [[NSMutableArray alloc] init];
[tickerNames addObject:@"ibm"];
[tickerNames addObject:@"ppg"];
[tickerNames addObject:@"google"];
[tickerNames addObject:@"vrzn"];
[tickerNames addObject:@"apple"];
[tickerNames addObject:@"barq"];
// Create and add the stocks to the portfolio
for (int i = 0; i < 6; i++) {
id newStock;
// Coin flip to determine type
NSUInteger randomType = random() % 2;
if (randomType == 0) {
newStock = [[BNRStockHolding alloc] init];
} else {
newStock = [[BNRForeignStockHolding alloc] init];
newStock.conversionRate = globalConRate;
}
// Assign remaining values
newStock.purchaseSharePrice = 15 * (random() % i);
newStock.currentSharePrice = newStock.purchaseSharePrice * 1.4;
NSUInteger randomTickerValue = random() % [tickerNames count];
newStock.symbol = tickerNames[randomTickerValue];
[tickerNames removeObjectAtIndex:randomTickerValue];
[mikesPortfolio addHoldings:newStock];
}
}
else{} 块 newStock.conversionRate... 内的行给出了 Xcode 预编译错误,指出“找不到 __strong id 类型的对象的属性” - 我猜是因为它无法判断 newStock 是否真的会我刚刚宣布它是什么?但是 main.m 末尾的分配语句显示了相同的行错误,就好像 newStock 没有这些属性一样,即使两个类都可以访问它们。
我如何让 newStock 明白它肯定是一个具有这些属性但也可能具有与子类相关联的转化率的类?
我试过这个:
BNRStockHolding newStock; <-- starting with superclass
// Coin flip to determine type
NSUInteger randomType = random() % 2;
if (randomType == 0) {
newStock = [[BNRStockHolding alloc] init];
} else {
newStock = [[BNRForeignStockHolding alloc] init];
newStock.conversionRate = globalConRate;
}
这将使底线的错误消失,但仍无法在 else{} 块中的子类方法处编译。
我哪里做错了?
【问题讨论】:
-
任何时候你说“抛出错误”,你都需要指出你收到的错误,无论是在编译时还是运行时。
标签: objective-c inheritance scope