Question

I have a very strange problem, I have two classes the first one is a sub class of NSObject class it contains a method that add an object to its array. See the code below:

    #import "portfolio.h"

    @implementation portfolio


    -(void) addStockObject:(stockHolding *)stock
    {
        [self.stocks addObject:stock ];
    }

    +(portfolio *) alloc
    {
        return [self.superclass alloc];
    }

    -(portfolio *) init
    {
        self.stocks=[[NSMutableArray alloc]init];
        return self;
    }

    -(NSString *)getCurrentValue
    {

        stockHolding *stockInArray;
        float currentValue=0.0;

        for (NSInteger *i=0; i<[self.stocks count]; i++) {
            stockInArray = [self.stocks objectAtIndex:i];
            currentValue+=stockInArray.currentValue;

        }
        return [NSString stringWithFormat:@"Current Value: %f",currentValue];
    }
    @end

so when i call the method -(void) addStockObject:(stockHolding *)stock, i get the following error(during runtime):

    Terminating app due to uncaught exception 'NSInvalidArgumentException',
    reason: '-[NSObject addStockObject:]: unrecognized selector 
    sent to instance 0x8b48d90'

The calling code is:

     p=[[portfolio alloc]init];
     [p addStockObject:s];
     portfolio *p;

anyone can tell me what is wrong?

the other class has a property and it seems that it can not access it during compile time. I'm really confused.

Thank you, missa

Was it helpful?

Solution

First, never override +(portfolio *) alloc.

Second, init methods must call another init method and you must always check self for nil before setting ivars. Apple recommends against using properties to set ivars in init methods and init methods should always return instancetype in compilers that support it or id in those that don't.

-(instancetype) init
{
    self = [super init];
    if (self)
    {
        _stocks = [[NSMutableArray alloc] init];
    }
    return self;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top