Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Cocoa, what is the purpose of the main.m class?

It just sits there... How do I run code independently of UI actions (as in, not only in response to a button push)? I'm trying to initialize some objects and run some scripts BEFORE i awakeFromNib. How do I do this?

like image 451
demonslayer319 Avatar asked Nov 28 '22 19:11

demonslayer319


1 Answers

In Cocoa, what is the purpose of the main.m class?

None, because there isn't one.

For one thing, the .m file is not the class. Neither is the .h. The practice of putting a class's @interface in a .h (header) file and its @implementation in a .m (implementation) file is a convention, nothing more. It's a good convention, but it's not enforced by the language.

So, a .m file contains zero or more class implementations. Usually, it's exactly one. Sometimes it's two, where the other is a small private class whose @interface is also in the same file.

main.m contains no classes. It usually only contains one function, which is named main.

main comes from C (of which Objective-C is a superset), and is the entry point of the program: It's where the program starts running. Everything happens here, or in a function called from here. A command-line tool will usually exit here as well, by main returning.

Most main functions in Cocoa apps are the default one that comes with the project template; this implementation simply tail-calls NSApplicationMain, which sets up the shared NSApplication object and starts it running. That function never returns; when the user quits a Cocoa app, the process simply exits.

You may want to read this list of important facts about Cocoa and Objective-C that I wrote. It sounds like you have some misconceptions (probably brought over from another framework you're more familiar with) that that list can clear up for you.

How do I run code independently of UI actions (as in, not only in response to a button push)?

That depends on when you are trying to do it. A periodic action, for example, would be a job for a timer.

I'm trying to initialize some objects and run some scripts BEFORE i awakeFromNib. How do I do this?

You could do it in initWithCoder:, which is sent to every non-view-layer object instantiated from an archive, including yours. Nibs are archives, too.

You might also consider being the application delegate and implementing a applicationWillFinishLaunching: method.

A third way would be to stuff the code in main. Note that practically any Cocoa code here is likely to log “no autorelease pool” warnings unless you wrap it in an @autoreleasepool statement; other solutions don't have this problem because NSApplication has already created an autorelease pool for you.

like image 175
Peter Hosey Avatar answered Dec 06 '22 00:12

Peter Hosey