客观C错误实例化一个类对象

时间:2013-11-05 02:47:44

标签: objective-c xcode5

有人可以告诉我以下程序有什么问题

#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;
}

我一直收到这个错误:

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

为什么我不能实例化一个类对象

2 个答案:

答案 0 :(得分:2)

改变这个:

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

对此:

myFrac = [[Fraction alloc] init];

如果你不想窝,我认为你需要这样做:

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

但最好是嵌套。虽然,只要Fraction是自定义类,您就应该创建自己的factory method。 ;)

此外,您的get方法实际上应该被称为set方法(甚至更好,请使用@properties)。

答案 1 :(得分:2)

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

毫无意义,应该是

myFrac = [[Fraction alloc] init];