Objective C程序没有编译

时间:2011-06-21 01:22:51

标签: objective-c gcc

我目前在电脑上学习目标c,我的程序无法编译。这是我得到的错误。 “Interface.m:In function' - [Person print]':Interface.m:17:2:error:找不到'NXConstantString'的”intergace声明“

我正在使用gcc编译器。

这是我的程序

 #import <Foundation/NSObject.h>
 #import <stdio.h>

@interface Person : NSObject {
    int age;
    int weight;
}

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

@end    

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

int main(int argc, char * argv[]){

    Person *person;

    person = [Person alloc];    
    person = [person init];

    [person setAge: 16];
    [person setWeight: 120];
    [person print];
    [person release];

    return 0;

}

1 个答案:

答案 0 :(得分:3)

@"I am %i years old and I weigh about %i pounds"等文字字符串(默认情况下)类型为NSConstantString,但您不会导入声明该类的头文件。

您可以添加:

#import <Foundation/NSString.h>

或者只是导入Foundation框架中的所有标题:

#import <Foundation/Foundation.h>

编辑:我刚刚注意到您使用的是Objective-C字符串作为printf()的参数:

printf(@"I am %i years old and I weigh about %i pounds",age,weight);

那不对; printf()需要一个C字符串,例如:

printf("I am %i years old and I weigh about %i pounds",age,weight);

你也可以使用NSLog(),它确实需要一个Objective-C字符串:

NSLog(@"I am %i years old and I weigh about %i pounds",age,weight);