2011-11-02 37 views
0

我仍然在新的編程objective-c,我得到這個例外,但我不知道這是什麼意思, 唯一的例外是在這裏,和之後存在的代碼..NSInvalidArgumentException編程iphone

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; 

} 

回答

8

這是錯誤的:

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

頁頭是一個類的方法時,init是一個實例方法,你也應這樣做

adham = [[Person alloc] init]; 

,在年底

[pool release]; 
[pool retain]; 

看你的兩條線爲什麼要保留NSAutoreleasePool?你不應該(事實上你應該會崩潰)。釋放池並返回。

1

這應該被拆分這樣,

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