我有一个运行良好的程序,但即使我在main.m中有一个NSLog文件,我也没有打印输出你能告诉我什么是错的吗?谢谢。
的main.m
#import <Foundation/Foundation.h>
#import "Stockholding.h"
int main(int argc, const char * argv[])
{
@autoreleasepool {
StockHolding *stockA;
StockHolding *stockB;
StockHolding *stockC;
[stockA setPurchaseSharePrice:2.40];
[stockA setCurrentSharePrice:3.12];
[stockA setNumberOfShares:40];
[stockB setPurchaseSharePrice:1.50];
[stockB setCurrentSharePrice:1.41];
[stockC setNumberOfShares:35];
[stockC setPurchaseSharePrice:1.10];
[stockC setCurrentSharePrice:1.20];
[stockC setNumberOfShares:60];
NSArray *holdings = [NSArray arrayWithObjects:stockA, stockB, stockC, nil];
for (StockHolding *n in holdings) {
// Call the methods
float cost = [n costInDollars];
float value = [n valueInDollars];
NSLog(@"Bought stock for $%.2f, It is now at $%.2f, I have %d shares, They cost me $%.2f, Now they are worth $%.2f", [n purchaseSharePrice], [n currentSharePrice], [n numberOfShares], cost, value);
}
}
return 0;
}
StockHolding.h
#import <Foundation/Foundation.h>
@interface StockHolding : NSObject {
float purchaseSharePrice;
float currentSharePrice;
int numberOfShares;
}
@property float purchaseSharePrice;
@property float currentSharePrice;
@property int numberOfShares;
-(float)costInDollars;
-(float)valueInDollars;
@end
StockHolding.m
#import "StockHolding.h"
@implementation StockHolding
@synthesize purchaseSharePrice, currentSharePrice, numberOfShares;
-(float)costInDollars
{
return (purchaseSharePrice * numberOfShares);
}
-(float)valueInDollars
{
return (currentSharePrice * numberOfShares);
}
@end
答案 0 :(得分:2)
您实际上并未创建任何StockHolding
个对象。因此,您的数组为空,循环不执行任何操作。
StockHolding *stockA;
只是指针的声明。您需要创建它指向的对象;通常的程序是:
StockHolding *stockA = [[StockHolding alloc] init];
因为在ARC下,对象指针被初始化为nil
(意思是“没有对象”),所以你将nil
作为所有参数传递给arrayWithObjects:
。 nil
是哨兵值意味着“没有更多参数”,数组是在没有内容的情况下创建的。
对于空数组,for (StockHolding *n in holdings)
没有任何可以枚举的内容,因此循环体中的所有代码(包括NSLog()
)都不会被执行。