实例化类对象的客观C错误

用户名

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

#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

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

写作

更改此:

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

对此:

myFrac = [[Fraction alloc] init];

如果您不想嵌套,我认为您需要这样做:

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

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

此外,您的get方法set实际上应该称为方法(或者甚至可以更好地使用@properties)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章