I have a program which runs fine, but I get no print output even though I have a NSLog file in main.m Can you tell me what’s wrong? Thank you.
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
You haven’t actually created any of those
StockHoldingobjects. Thus, your array is empty, and the loop doesn’t do anything.is just a declaration of a pointer. You need to create the object to which it points; the usual procedure is this:
Since, under ARC, object pointers are initialized to
nil(which means “no object”), you are passingnilas all of the arguments toarrayWithObjects:.nilbeing the sentinel value meaning “there are no more arguments”, the array is created without contents.With an empty array,
for (StockHolding *n in holdings)doesn’t have anything to enumerate over, so none of the code in the body of the loop, including yourNSLog(), gets executed.