user1801279
user1801279

Reputation: 1783

objective C error instantiating a class object

could someone please tell me what is wrong with the following program

#import <Foundation/Foundation.h>

@interface Fraction:NSObject

-(void)getNumerator: (int) numerator;
-(void)getDenominator: (int) denominator;
-(int) calculate;

@end


@implementation Fraction
{
    int num;
    int den;
    int result;
}

-(void) getDenominator:(int)denominator{
    den=denominator;

}

-(void) getNumerator:(int)numerator{
    num=numerator;
}

-(void) calculate{
    result = num/den;
    NSLog(@"%i",result);
    //return result;
}

@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {

        Fraction *myFrac;
        // insert code here...
        myFrac = [Fraction alloc];
        myFrac = [Fraction init];
        [myFrac getNumerator:4];
        [myFrac getDenominator:6];
[myFrac calculate];
//        NSLog(@"the result is %i",result);
        NSLog(@"Hello, World!");


    }
    return 0;
}

I keep getting this error :

roject3[523:303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[Fraction<0x100001200> init]: cannot init a class object.'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff8a01641c __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x00007fff824d5e75 objc_exception_throw + 43
    2   CoreFoundation                      0x00007fff8a019650 +[NSObject(NSObject) dealloc] + 0
    3   project3                            0x0000000100000e0c main + 108
    4   libdyld.dylib                       0x00007fff826b35fd start + 1
    5   ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Why cannot I instantiate a class object

Upvotes: 0

Views: 129

Answers (2)

nhgrif
nhgrif

Reputation: 62052

Change this:

myFrac = [Fraction alloc];
myFrac = [Fraction init];

To this:

myFrac = [[Fraction alloc] init];

If you don't want to nest, I think you need to do it this way:

myFrac = [Fraction alloc];
myFrac = [myFrac init];

But it is better to just do it nested. Although, as long as Fraction is a custom class, you should create your own factory method. ;)

Also, your get methods should be called set methods actually (or even better, use @properties).

Upvotes: 2

Bryan Chen
Bryan Chen

Reputation: 46578

myFrac = [Fraction alloc];
myFrac = [Fraction init];

make no sense, should be

myFrac = [[Fraction alloc] init];

Upvotes: 2

Related Questions