Pregunta

I'm currently teaching myself Objective-C as a first language. I understand the difficulty involved, but I'm quiet a persevering individual. I've began to do the exercises on the Apple Objective-C documentation. My goal is to have my program log out my first and last name instead of a generic Hello World greeting.

I keep receiving a Use of Undeclared identifier error. I'm trying to figure out what is causing the error.

Here is the 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

Here is 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
¿Fue útil?

Solución

The problem is that fullName is the name of a method. It should be invoked on self with square brackets.

Since saySomething: expects a single parameter, you need to either (1) remove the @"Hello %@" portion of the call, like this:

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

or to make a single string from @"Hello %@" and [self fullName], like this:

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

Otros consejos

You are passing back a string of first and last name but I don't see anywhere that you had set a value for them. As others noted try

    -(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];
    }

use

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

or

[self saySomething:@"Hello %@", [self fullName]];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top