错误:语义问题:一元表达式的参数类型“NSString *”无效

时间:2012-01-08 21:25:33

标签: objective-c nsstring undeclared-identifier

在解决标识符错误后,我想,我现在已经生成了以下错误,但我看不出我出错的地方......

根据我所学到的,这应该有用......但是会产生错误......奇怪的是我遇到的每个例子都不同?那么有没有正确的方法来使用函数?

在以下Student.h文件中找到

错误:语义问题:无效的参数类型'NSString *'到一元表达式

错误:解析问题:预期表达式

我对编码非常陌生,经验有限,所以任何解决这个问题的建议都会受到赞赏......以及学习曲线......

由于

Student.h(看起来像这样)

#import < Foundation/Foundation.h >

@interface Student : NSObject {
@private

NSString *name;
NSString *gender; 
NSString *getStudentCategory;
int age;
}
@property (nonatomic,retain) NSString *name;
@property (nonatomic,retain) NSString *gender;
@property (nonatomic) int age;

- (NSString *)getStudentCategory;

@end

Student.m(看起来像这样)

#import < Foundation/Foundation.h >
#import "Student.h"

@implementation Student
@synthesize name,gender,age;

- (id)init
{
self = [super init];
if (self) { 

    - (NSString *)getStudentCategory  //*ERROR: Semantic Issue: Invalid argument type 'NSString *' to unary expression*
    {
        NSString *studentCategory;
    if (age <=12) 
        studentCategory = @"Primary School Student.";
    else if (age >=13 && age <=17)            //*Error: Parse Issue: Expected expression*
        studentCategory = @"Secondary School Student.";
    else if (age >=18)                       //*Error: Parse Issue: Expected expression*
        studentCategory = @"College Student.";
    }
return self;
}

@end   

main.m(看起来像这样)

#import < Foundation/Foundation.h >
#import "Student.h"

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

    Student *pupil =[[Student alloc] init];

        pupil.name = @"john";
        pupil.gender = @"male";
        pupil.age = 20; 

        NSLog([NSString stringWithFormat:@"Name: %@, Gender: %@, age %d",pupil.name,pupil.gender,pupil.age]); 

        NSLog([pupil getStudentCategory]);

    }
return 0;

}

我从Student.m中删除了:

- (id)init
{
self = [super init];
if (self) 

它有效吗?为什么? : - /

有什么想法吗? : - )

2 个答案:

答案 0 :(得分:1)

嗯,这是一个问题:

- (id)init
{
self = [super init];
if (self) { 
    // WHAT IS THIS CHICANERY?!
    - (NSString *)getStudentCategory  //*ERROR: Semantic Issue: Invalid argument type 'NSString *' to unary expression*
    {
        NSString *studentCategory;
    if (age <=12) 
        studentCategory = @"Primary School Student.";
    else if (age >=13 && age <=17)            //*Error: Parse Issue: Expected expression*
        studentCategory = @"Secondary School Student.";
    else if (age >=18)                       //*Error: Parse Issue: Expected expression*
        studentCategory = @"College Student.";
    }
return self;
}

我不知道从- (NSString *)getStudentCategory开始的行是什么。您似乎正在尝试在另一种方法中定义方法,但您无法做到这一点。

答案 1 :(得分:0)

编译器的错误消息将告诉您未声明的标识符是什么。它是否告诉你“NSString”是未宣布的?如果是这样,请确保在使用之前导入<Foundation/Foundation.h><Cocoa/Cocoa.h>