Objective-C练习未申报的标识符错误



我目前正在教自己作为第一语言。我了解所涉及的困难,但我安静了一个坚持不懈的人。我已经开始在Apple Objective-C文档上进行练习。我的目标是让我的程序注销我的名字和姓氏,而不是通用的Hello World问候。

我不断收到未申报的标识符错误的使用。我试图弄清是什么原因导致错误。

这是Introclass.h

    #import <UIKit/UIKit.h>
    @interface XYZperson : NSObject
    @property NSString *firstName;
    @property NSString *lastName;
    @property NSDate *dateOfBirth;
    - (void)sayHello;
    - (void)saySomething:(NSString *)greeting;
    + (instancetype)person;
    -(int)xYZPointer;
    -(NSString *)fullName;
    @end

这是Introclass.m

#import "IntroClass.h"
@implementation XYZperson
-(NSString *)fullName
{
    return[NSString stringWithFormat:@" %@ %@", self.firstName, self.lastName];
}
-(void)sayHello
{
    [self saySomething:@"Hello %@", fullName]; //use of undeclared identifier "fullName"
};
-(void)saySomething:(NSString *)greeting
{
    NSLog(@"%@", greeting);
}
+(instancetype)person{
   return [[self alloc] init];
};
- (int)xYZPointer {
    int someInteger;
    if (someInteger != nil){
        NSLog(@"its alive");
    }
    return someInteger;
};

@end

问题是 fullName是方法的名称。应该在self上使用方括号调用它。

由于saySomething:期望一个参数,因此您需要(1)删除呼叫的@"Hello %@"部分,如以下:

-(void)sayHello {
    [self saySomething:[self fullName]];
};

或从@"Hello %@"[self fullName]制作单个字符串,例如:

-(void)sayHello {
    [self saySomething:[NSString stringWithFormat:@"Hello %@", [self fullName]]];
};

您正在将一个和姓氏的字符串传递回一个字符串,但我看不到您为它们设置值的任何地方。正如其他人所指出的那样尝试

    -(void)sayHello
    {
         _firstName = [NSString stringWithFormat:@"John"];
         _lastName = [NSString stringWithFormat:@"Doe"];
         //if you want to see what's happening through out your code, NSLog it like
        NSLog(@"_firstName: %@ ...", _firstName);
        NSLog(@"_lastName: %@ ...", _lastName);
        NSString *strReturned = [self fullName];
        NSString *concatStr = [NSString stringWithFormat:@"Hello %@", strReturned];
        NSLog(@"strReturned: %@ ...", strReturned);
        NSLog(@"concatStr: %@ ...", concatStr);
        [self saySomething:concatStr]; 
    };
    -(NSString *)fullName
    {
        return[NSString stringWithFormat:@" %@ %@", self.firstName, self.lastName];
    }

使用

[self saySomething:@"Hello %@", self.fullName]];

[self saySomething:@"Hello %@", [self fullName]];

相关内容

  • 没有找到相关文章

最新更新