sophisticatedRock
sophisticatedRock

Reputation: 3

Trouble with calling a method in Objective C (Apple Documentation example)

I'm following along with Apple's "Programming with Objective C" document, the link being: https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/WorkingwithObjects/WorkingwithObjects.html#//apple_ref/doc/uid/TP40011210-CH4-SW1

Anyways, I've gotten to the point where it ask for calling the sayHello method.

"Create a new XYZPerson instance using alloc and init, and then call the sayHello method."

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

int main(int argc, const char * argv[]);

XYZPerson *firstPerson = [[XYZPerson alloc] init]; //Initializer element is not a lime-time constant
[firstPerson sayHello]; //No Visible @interface for 'XYZPerson' delcares the selector 'sayHello'

@implementation XYZPerson
- (void)sayHello {
    [self saySomething:@"Hello, World"];
}

- (void)saySomething: (NSString *)greeting {
    NSLog(@"%@", greeting);
}

@end

I believe I'm having a misunderstanding with how apple is explaining the work or just have no clue.

Wishing apple had these examples done for us to review over.

Upvotes: 0

Views: 50

Answers (2)

badAPI
badAPI

Reputation: 122

You need to put the code inside the main function. Right now you have the code just sitting in your file, outside of any function. It should be:

int main(int argc, const char * argv[]) {
    XYZPerson *firstPerson = [[XYZPerson alloc] init];
    [firstPerson sayHello];
}

Also, according to the docs you should have a separate main.m file that has your main function inside of it.

Upvotes: 0

Muhammad Waqas Bhati
Muhammad Waqas Bhati

Reputation: 2805

As you can only access public functions which are declared in .h file with the class object.

Kindly declare that function in .h file and it will solve your problem

Upvotes: 0

Related Questions