Challenge: 'Incompatible pointer types' & Importing


#1

Attempting to ‘build on’ the code from the last challenge, the data model contains 3 stocks and 1 foreign stock with a conversion rate.

My version of the program prints each stock, number of shares & value in dollar and then prints the total value of the portfolio in dollars.

Question 1. What is causing the warnings: incompatible pointer types sending ‘StockHolding *__strong’ to parameter of type ‘ForeignStockHolding *’ to the 3 (non foreign) stocks?
If I remove ‘Foreign’ from the declaration - (void)addStock:(ForeignStockHolding *)aStock (Portfolio.h), but leave it in the name of the method in the implementation, the program runs with no warnings. E.g.
Portfolio.h:

  • (void)addStock:(StockHolding *)aStock;
    Portfolio.m:
  • (void)addStock:(ForeignStockHolding *)aStock {

    }

[code]
// Portfolio.h

#import <Foundation/Foundation.h>
#import “ForeignStockHolding.h”

@interface Portfolio : NSObject
{
NSMutableArray *portfolio;
}

  • (void)addStock:(ForeignStockHolding *)aStock;
  • (void)displayPortfolio;

@end[/code]

// Portfolio.m

#import "Portfolio.h"

@implementation Portfolio

- (void)addStock:(ForeignStockHolding *)aStock {
    if ( !portfolio )
    {
        portfolio = [[NSMutableArray alloc] init];
    }
    [portfolio addObject:aStock];
}

- (float)portfolioValue {
    float total = 0;
    NSLog(@"\nStock  Shares  Value(USD)");
    for (ForeignStockHolding *stock in portfolio)
    {
        NSLog(@"\n%@\t%.2d\t\t%.2f", [stock name], [stock numberOfShares], ([stock valueInDollars] * [stock numberOfShares]));
        total = ([stock numberOfShares] * [stock valueInDollars]);
    }
    return total;
}

@end

Question 2: What is the proper way to put these import statements? Is this correct? (Can someone talk to this?)
In main:

#import <Foundation/Foundation.h>
#import “StockHolding.h”
#import “ForeignStockHolding.h”
#import “Portfolio.h”

In StockHolding.h:

#import <Foundation/Foundation.h>

In ForeignStockHolding.h:

#import <Foundation/Foundation.h>
#import “StockHolding.h”

In Portfolio.h:

#import <Foundation/Foundation.h>
#import “StockHolding.h” (optional)
#import “ForeignStockHolding.h”

Thanks for inputs.


#2

After re-reading the employees class in chapter 18, I realized that the program runs error-free if the imports are structured:
In Portfolio.h,
#import “ForeignStockHolding.h”

In ForeignStockholding.h,
#import “StockHolding.h”

In StockHolding.h,
no import

And in main() simply,
#import "Portfolio.h

It appears to me like a chain. Obviously, this trend will break with more complicated programs. Is it like leaves (Portfolio), branches (Foreign… & StockHolding) & trunk (main) on a tree?

Also, each time we create a new class, we are getting the redundant #import <Foundation/Foundation.h> which isn’t really necessary. Can it be safely removed?

Trying to learn good practices through this question. Thanks again.