Ok, I'm totally new to obj-c + cocoa, so this is probably obvious, but here goes:
I've been moving from command line apps to cocoa apps in learning how to work with objective-c in Xcode. One thing I don't really understand is the role of the AppDelegate and how it connects to main.m
It seems like you could put your entire program in the appdelegate and it would run fine, and you don't even need main.m, but not the other way around, if you're making a cocoa app you have to at least have the appdelegate.
I've done a lot of php web development and command-line tools, so I guess what I'm looking for is the file that the program will execute first and is intended to "control" the rest of them.
Can anyone help me understand what's going on in a Cocoa program, how AppDelegate and main.m are (or are not) related, and what the flow of the program is supposed to be?
main.m
contains the main()
function, which is the entry point for the program, it's run first. Then it calls UIApplicationMain()
, which does the OS-specific application setup stuff, and loads the main Interface Builder .xib
file which contains your app delegate instance.
That is, without main.m
your app delegate wouldn't even get loaded.
A key feature of many object-oriented systems (such as Cocoa) is "inversion of control", which basically means that the framework is running everything, and any code you write is under its control.
So, unlike PHP, you don't write the code that executes at startup. What you do is define methods for the app delegate, controllers, views, and other objects, and let the framework invoke those methods as it needs to do so. You will never see the overall "flow of control" throughout the program; you will only see it as control flows into your pieces of the program.
This can be confusing at first, as you try to figure out how to trick the framework into calling your code at the times and in the order you expect, but in the long run it actually makes things easier, as you can trust the framework to take care of a lot of things for you.
In a Cocoa app, a lot of the logic of the app will actually be in view controllers, rather than in the app delegate. The app delegate generally handles startup and shutdown responsibilities, but other objects do most of the work between startup and shutdown. So don't try to squeeze everything into the app delegate.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With