2011-11-02 1 views
0

Je suis encore nouveau dans la programmation objective-c, j'ai cette exception, mais je ne sais pas ce que cela signifie, L'exception est là, et après il y a le code ..NSInvalidArgumentException dans la programmation 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 

et voici le code qui provoque cette exception, ce code est de créer seule classe (interface) et fait une instance de ces valeurs de consigne de classe .. t et u

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

} 

Répondre

8

Ceci est faux:

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

alloc est une méthode de classe, init est une méthode d'instance, vous devez faire ce

adham = [[Person alloc] init]; 

Aussi, en regardant vos deux lignes à la fin

[pool release]; 
[pool retain]; 

pourquoi retenez-vous le NSAutoreleasePool? vous ne devriez pas être (vous devriez avoir un accident en fait). Relâchez la piscine et revenez.

1

Cela devrait être divisé comme celui-ci,

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