user3358392
user3358392

Reputation: 17

Objective-c Object not returning or print string

I'm new to objective c and im having some problems with objects.

I believe the syntax of the program is correct but it doesn't seem to return any values or even output (NSLog) from within the method.

Any help would be greatly appreciated :)

#import <Foundation/Foundation.h>

@interface XYZPerson : NSObject

- (NSString *)sayHello;

@end

@implementation XYZPerson

- (NSString *)sayHello {
    NSString *test = @"test";
    return test;

}

@end


int main(int argc, const char * argv[])
{
    XYZPerson *newPerson;
    NSString *getString = [newPerson sayHello];
    NSLog(@"the returned string is :%@", getString);
    return 0;
}

Upvotes: 0

Views: 64

Answers (3)

Henry F
Henry F

Reputation: 4980

Add in:

newPerson = [[XYZPerson alloc] init];

Right underneath:

XYZPerson *newPerson;

You never initialized the XYZPerson object, and that is why it is returning null.

Upvotes: 0

Bryan Chen
Bryan Chen

Reputation: 46598

you have to create an instance of XYZPerson and assign it to newPerson

newPerson = [[XYZPerson alloc] init];

otherwise newPerson is nil and calling method on nil always return nil

Upvotes: 2

Michael Dautermann
Michael Dautermann

Reputation: 89509

"newPerson" is null when you call it.

You need to do:

newPerson = [[XYZPerson alloc] init];

before calling a method on it.

Upvotes: 2

Related Questions