A couple brief syntax questions


First, a quick one…

The (Asset *) is the type declaration for the “a” argument? Am I understanding this correctly? Why does Asset * need the parentheses?

Ok…now onto the longer one:

[code]#import “Portfolio.h”
#import “StockHolding.h”

@implementation Portfolio

  • (void) addStockObject:(StockHolding *)stock
    if (!stockPortfolio)
    // Create the array if it doesn’t exist
    stockPortfolio = [[NSMutableArray alloc] init];
    [stockPortfolio addObject:stock];

  • (float) portfolioValue
    // Initialize a variable to hold the full value of the portfloio of stocks
    float portfolioValue = 0;
    for (StockHolding *s in stockPortfolio)
    float stockValue = [s valueInDollars];
    portfolioValue += stockValue;
    return portfolioValue;

The above code is what I wrote in the Portfolio.m file of my Portfolio class for the challenge. Everything worked as expected, but I had a really hard time writing the 1st method (addStockObject). In the spot where I had to create the array (right after the “if”) I wanted to write:

or maybe:

So why is it that this…:

…was ultimately correct? Why don’t I need the type hint at the beginning of the line? …the NSMutableArray…


Because arguments in Objective C need to be typecast. It’s not any different than C++ where an argument is specified as (int whatever). The parentheses cast the type the method expects.

[quote]So why is it that this…:
stockPortfolio = [[NSMutableArray alloc] init];

…was ultimately correct? Why don’t I need the type hint at the beginning of the line? …the NSMutableArray…[/quote]

Remember the implementation file (or section) imports your header file. The class Portfolio has already (presumably) been declared to include an NSMutableArray named stockPortfolio. All that remains is to implement the methods required to set that value correctly in the Portfolio.m method. You don’t re-declare stockPortfolio in the implementation when it’s already been declared in the header (and thus already expected).

You’re defining a method used by your Portfolio class. All Portfolios have previously been declared to include an NSArray called stockPortfolio. Now you’re just defining what Portfolio can do with its stockPortfolio (initializing it is a good start!)


So do the parentheses around (Asset *) serve a function, or are they just there for organization?

Like in C, when we declare the type for a pointer like as in the following:

I notice we don’t need to write it like this:

It’s the same idea though, right?


Lol, I don’t suppose you’ll settle for “because that’s the way it is”? In Objective C, arguments to a method are typecast. I’m sure it has something to do with the language being a superset of C and distinguishing obj c methods from c functions, but the why of that really doesn’t matter to us, does it? That’s the syntax :slight_smile:


Haha! Thanks! I’m just a PITA about those kinds of things… :smiley: