0

Objective C: I have an NSMutableArray with 3 objects of a class stockHolding

the class has a method valueInDollars which returns the product of (numberOfShares * shareMktVlue)

The for loop (below) attempts to dynamically call the method valueInDollars for each element in the Array as follows:

NSUInteger itemCount = [stockHolding count];

for (int i = 0; i < itemCount; i++) {
    NSString *itemd = [stockHolding objectAtIndex:i];
    float mktValue = [AAPL valueInDollars];  
}

The question is: How can AAPL be declared dynamically so that it changes for each loop iteration to the stock symbol object in the array.

I tried to replace AAPL with "itemd" in the code above, but get the error message:

"NSString may not respond to valueInDollars"

Any help here would be appreciated.

3
  • 3
    Sounds like you have an array of strings not an array of StockHolding objects Commented Dec 11, 2011 at 23:44
  • I wold love to help with this, but I have a few questions. What is the name of the class? What is the name of the array? What are you trying to accomplish with this loop? What is the purpose of the NSString? What does APPL represent in the code? Thanks. Commented Dec 11, 2011 at 23:51
  • Can you post the output if you add NSLog(@"%@", itemd); after NSString *itemd = [stockHolding objectAtIndex:i]; please. Commented Dec 12, 2011 at 8:54

2 Answers 2

1

Your code sample seems to indicate that your NSMutableArray is called stockHolding, whereas your question text indicates that stockHolding is the class of the objects in the array. If we assume that the array name is correct and the objects in it are of class StockHolding then the following should work (using Objective-C 2.0 fast enumeration):

for (StockHolding *stock in stockHolding) {
    float mktValue = [stock valueInDollars];
    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

First: sjs's answer is correct and I always prefer this solution.

Another solution would be:

NSUInteger itemCount = [stockHolding count];

for (int i = 0; i < itemCount; i++) {
    id itemd = [stockHolding objectAtIndex:i];
    float mktValue = [AAPL valueInDollars];  
}

or:

NSUInteger itemCount = [stockHolding count];

for (int i = 0; i < itemCount; i++) {
    StockHolding *itemd = [stockHolding objectAtIndex:i];
    float mktValue = [AAPL valueInDollars];  
}

Note:
You should call your array stockHoldings instead of stockHolding. You should use pluralization.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.