编程iphone中的NSInvalidArgumentException

时间:2011-11-02 10:17:25

标签: iphone objective-c xcode

我仍然是objective-c编程的新手,我得到了这个例外,但我不知道它是什么意思, 例外是在这里,之后是代码..

Running…
2011-11-02 12:10:31.923 app3[1322:a0f] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[Person<0x100001098> init]: cannot init a class object.'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x00007fff8499c7b4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x00007fff84729f03 objc_exception_throw + 45
    2   CoreFoundation                      0x00007fff849f5f29 +[NSObject(NSObject) init] + 137
    3   app3                                0x0000000100000d99 main + 124
    4   app3                                0x0000000100000c60 start + 52
    5   ???                                 0x0000000000000001 0x0 + 1
)
terminate called after throwing an instance of 'NSException'
Program received signal:  “SIGABRT”.
sharedlibrary apply-load-rules all

这里是导致此异常的代码,此代码只是创建类(接口)并使该类的实例设置为t和..

#import <Foundation/Foundation.h>
#import <Foundation/NSObject.h>
@interface Person:NSObject{

    int age;
    int weight;
}

-(void) print;
-(void) setAge:(int) a;
-(void) setWeight:(int) w;

@end


@implementation Person
-(void) print{
    NSLog(@"I am %i years old and weight %i pound",age,weight);
}
-(void) setAge:(int) a{
    age = a;
}
-(void) setWeight:(int)w{
    weight = w;
}
@end

int main(int argc, char *argv[]){
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc]init];
    Person *adham;
    adham = [Person alloc];
    adham = [Person init];
    [adham setAge:24];
    [adham setWeight:68];
    [adham print];
    [pool release];
    [pool retain];
    return 0;

}

2 个答案:

答案 0 :(得分:8)

这是错误的:

adham = [Person alloc];
adham = [Person init];

alloc是一个类方法,init是一个实例方法,你应该这样做

adham = [[Person alloc] init];

另外,最后看看你的两行

[pool release];
[pool retain];

为什么要保留NSAutoreleasePool?你不应该(事实上你应该崩溃)。释放游泳池并返回。

答案 1 :(得分:1)

应该像这样分开,

Person *adham;
adham = [Person alloc]; // alloc is a class method
adham = [adham init]; // init is an instance method