Tom Jacky
Tom Jacky

Reputation: 203

In Objective-C, how to use 'self' in main() function?

I have the definition:

@interface MyClass: NSObject
{
   NSString *str;
   id delegate;
}
-(id)initWithStr:(NSString *)str
        delegate:(id)delegate;
@end

and when i send message to my object in the main.m like this:

int main(int argc, const char * argv[])
{
    @autoreleasepool {
       [[MyClass alloc] initWithStr:@"abc-xyz"
                           delegate:self];
    }
}

There is the error "Use of undeclared identifier 'self' ". I m a newb of objective-c and I know that the 'self' indicates the receiver of the message, but i don't know how to use it in the main() function. Can anybody tell me what's wrong about it and how to fix it?

Upvotes: 3

Views: 3457

Answers (3)

Raphael Ayres
Raphael Ayres

Reputation: 894

What happens is that self points to the executing object. main function is not in a class, so, YOU CAN`T call self on a function, only on a method of a class. What are you really trying to do? Use the AppDelegate. When you create a new project, Xcode already gives you some files. One of then is called (YOUR_PROJECT)AppDelegate. This is the starting point of your application.

If you have any customizations to do in the initialization of your app, find your AppDelegate.m file, look for - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method, and place your code inside this method.

Never mess up with main.m file.

EDIT:

For Mac OS X here's what you should do:

Create a class to act as a delegate and add that class to the delegate.

 MyDelegate * d;
 MyClass * c;

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

       d = [[MyDelegate alloc] init];

       c = [[MyClass alloc] initWithStr:@"abc-xyz"
                           delegate:d];
    }
}

Then, on MyDelegate, implement the callbacks of the protocol.

If you want to have a callback on main, you will have to use a function pointer. You'll have to enter in the world of plain C. I don't recommend since you want to use object oriented stuff. Don't mix both, or you'll create a monster.

Upvotes: 4

phlebotinum
phlebotinum

Reputation: 1130

In Objective-C, how to use 'self' in main() function?

This is impossible.

Because "self" can only be used by instances of objects. main() is a function. Functions are not objects but code "on its own".

Upvotes: -1

Mundi
Mundi

Reputation: 80273

You do not use the main() function like this.
Do this in the AppDelegate, then it will just work.

Upvotes: 0

Related Questions