Relationship between AppDelegate and main.m - objective-c

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.

Related

Is it possible to work without App Delegate?

My question is based on the fact that, one might have multiple smaller projects and then wants to integrate them into one bigger one, for coding efficiency.
I saw multiple project's where the App Delegate wasn't used at all, I think the Adium project was one of them. I also was a couple of times able to recreate it in the past, now I cannot remember how.
I figure a basic NSObject inherited class would fit, plus its instantiation and connections.
The question is, is it possible to work without App Delegate (or have a workaround)?
You need an app delegate, if you want to implement some of the methods declared in the NSApplicationDelegate protocol to respond to certain app life-cycle events. If you don't need to implement any of those, you don't need an app delegate. Some delegate methods also have notification alternatives.
OK, from your comment...
I mean having no additional code in AppDelegate
Then yes.
It is not only possible, it is recommended. Exactly for the reason that you have said.
The app delegate is there as a communication layer between the app and the OS. i.e. "the app has started", "the app is about to close", "the app just received a notification", etc...
All of these is what the app delegate is for.
The logic of your app should not go anywhere near you app delegate. Like you said, you may have different apps or different targets in your app that use different app delegates.
If you have code in there then you would have to duplicate it to each copy.
There are many other reasons too.
Here is a quick link... http://www.hollance.com/2012/02/dont-abuse-the-app-delegate/
There are many others about not using the app delegate.

Best design for assigning CoreLocation & CoreMotion updates through multithreading?

I have a Game class that has a -(void) play method which will be executed when the user clicks on the Play button on the device.
Inside the -(void) play method I have a while loop that will be executed repeatedly until the user clicks on the Quit button. This while loop is basically the core of my code, where all necessary methods are being called, things happen, objects interact etc.
I also have a User class (amongst other classes..) and I create a User* player instance in the -(void) play method of my Game class to store some values and have those interact with other things along the duration of the game..
Now I need to know (at any moment during the game..) the device's deviation from the magnetic North & the acceleration the user is exercising on the device
I've written the code and everything is working fine. However, being new to programming I have a few questions concerning the overall design of my code, which I think is a mess especially when it comes to using the CoreLocation & CoreMotion frameworks..
The -(void) play method of the Game class (which is basically my "main" method) is executed on a separate thread as in [game performSelectorInBackground:#selector(play) withObject:nil]; Is this the right way to do it?
However, I initialise CoreMotion Acceleration updates from inside the -(void) play method as in [motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]withHandler:^(CMDeviceMotion *motion, NSError *error){...} which means that updates will be stored in the main Queue whereas the method initializing these updates is executed from inside a method(-(void) play) that runs on a separate thread. Does that make sense?
I also initialise CoreLocation updates when I initialize an instance of my Game class. Even more weird?
My point is this. Given that I'll be measuring the acceleration the user is exercising on the device and the orientation he/she is giving to the device (degrees) I want to encapsulate all that in my User class and have methods like [player getMyDegrees]; and [player getMyAcceleration]; Isn't this the correct way design-wise? Where exactly should I initialize those updates? From inside which specific class-method? Should everything be running on the same main thread or the same separate thread or on different separate threads? I'm confused..
Threading is a complex issue, as you've no doubt seen.
The -(void) play method of the Game class (which is basically my
"main" method) is executed on a separate thread as in [game
performSelectorInBackground:#selector(play) withObject:nil]; Is this
the right way to do it?
It depends. Is there any work that you are doing in the -play method that absolutely must be taken off the main thread (i.e. crazy number crunching, server requests, loading textures, etc.) so as to make the UI more responsive? That's really the only reason methods are dispatched to the background on iOS, is to maintain a responsive UI, because UIKit classes are not just thread-unsafe, but they will wholeheartedly dive straight off a cliff and take your app with them if you try to do anything in the background.
However, I initialise CoreMotion Acceleration updates from inside the
-(void) play method ... which means... these updates are executed from inside a method(-(void) play) that runs on a separate thread. Does
that make sense?
Well, again it depends here. The ultimate goal of threading is not to have two or more threads attempt to access or mutate one object held by another thread, which is just the start of a whole mess of problems. The one thing that I have to take issue with is the fact that you are using the main queue despite a very clear and ominous warning in the documentation:
Because the processed events might arrive at a high rate, using the
main operation queue is not recommended.
This is an example of one of those high powered calculations that you should be throwing to a background thread, which is NSOperationQueue's forte.
I want to encapsulate all that in my User class and have methods like
[player getMyDegrees]; and [player getMyAcceleration]; Isn't this the
correct way design-wise? Where exactly should I initialize those
updates? From inside which specific class-method?
It depends on how design-wise you're trying to be, and what you consider good design. Good code is usually code that you could hand off to another programmer and have them pick up where you started off with very little effort. That being said, it sounds like your user class is going to be the controller part of MVC. If your classes are too bulky, cut 'em up. Classes in objective-c are surprisingly light-weight creatures. Even arranging one class in multiple categories that describe the general section's implementation are fine (the header of NSString for example).
Should everything be running on the same main thread or the same
separate thread or on different separate threads? I'm confused..
Everything UI and light should be running in the main thread (or main queue if that's how you prefer to look at it), and everything heavy and thread-blocking should be put in a background thread.

Core Data singleton manager?

What technical reasons are there not to make a singleton class to manage my Core Data? I'm trying to make a decision now, if I should strip out all of the boilerplate core data code and re-implement it in a singleton.
The boilerplate code in the application delegate in the Xcode templates is functionally implemented as a singleton. The application object is a singleton and it maintains but one delegate object so you've only got one instances of the Core Data stack and since the application object is universally accessible, you can always get to the app delegate as well.
However, even that works only for simple apps with one persistent store with all the context using that one store. In more complex apps you may have multiple stores or context so a singleton quickly becomes too bloated.
A singleton usually won't buy you much complexity hiding or save duplicate coding because most of the coding you have to do with Core Data is in the controller layer where you link up the model to the view/interface. Since that logic is usually custom to each view, you can't actually park it in the singleton.
I've used singletons in the past but in the end they usually prove more hassle than they are worth.
There are two important considerations (note these are not the only two) when deciding if a singleton is right for you:
Threading
Memory Usage
Threading
Singletons are convenient, but if your application uses multiple threads you might be tempted to write something like this:
[[CDSingleton managedObjectContext] executeFetchRequest:someFetch];
//later on a background thread you might write
NSManagedObject *object = [[CDSingleton managedObjectContext] objectWithID:objectID];
Shortly after that, your application will crash because you've accessed a managedObjectContext which was likely created on the main thread from some other thread.
Memory Usage
Singletons never go away, that's the point of a Singleton. Thus, they also never willingly free their consumed resources. In the case of CoreData that means the managed object context will continue to hold managed objects in memory until you call -reset or -save:.
That could be bad if your app uses a lot of data.
Best practice is to pass the managed object context between view controllers. Apple documentation and samples do that. You should never really have to access your app delegate, not for Core Data, not for anything.
http://www.cimgf.com/2011/01/07/passing-around-a-nsmanagedobjectcontext-on-the-iphone/

Confused about Xibs and programmatically

i a newbie for iphone development. I got some questions here.
I know IB is a convinience tool for UI desgin and you also can do most things programmatically. I am just wondering, when should I create an interface controll without IB and why so. I am trying to form a good habit for this. Thank you very much. A friend told me that when efficiency should be considered for the application, then i should create interface controller programmatically, any other cases?
I am studying Learn Objective c on Mac now. It says that "Apple suggests you avoid using autorelease on your own code". So, does it mean I cannot use "autorelease" or just i should avoid using it. For example, can i use following code in my own code for iphone development?
#Interface Test {
A* a;
}
#Implementation {
a = [[[A alloc]init]autorelease];
}
Thank you for your time to read this. I am looking forward to answers :D.
Sometimes creating custom controls will require you to build them programmatically.
No, it's not that you can not use autorealease, it's just that using it adds to the burden of memory management. But in some cases you probably don't have an option, such as when you have a method that returns a temporary object. Using retain/release method to manually control object lifespan is the recommended way of doing things in iPhone development. Please see Autorelease pool for more details.
See Matt Gallagher's blog post for a discussion of efficiency. Simply put, one method is probably no more efficient than the other. This depends on your specific application, of course. Generally speaking, do what is most comfortable in designing your user interface. Make optimizations as needed.
1) If you are doing basic views that interface building has the widgets ready to go for, then use interface builder, it will make your life easier. Plus if you are just starting out it will let you get some sample code out the door faster. I'm not a huge fan of interface builder, but if you have to maintain code, you'll come across it so good thing to get familiar with it.
2) I don't think that autorelease is a bad thing. If you are writing single threaded code there is not as much to worry about. However, the thing that can come back to bite you is that you don't actually know when things will be released. So if you have programmed poorly, and try to reference an object that you have autoreleased later in code then you may get inconsistent behavior. I autorelease, but I also am very good about retain/release in other parts of my code that is passed these objects.

what is the program flow in Cocoa Applcation

I am new to mac os X development ,I downloaded an open source mac application ,but i couldn't able to understand the flow of execution of cocoa program.so any one can explain the program flow of a general cocoa program briefly.
Thanks in advance
Start in main. It's not likely to contain anything interesting, but worth checking just in case. Most probably, it will contain only a call to NSApplicationMain, which will create the NSApplication object and send it a run message. That's what gets the application running, and this method will run for the rest of the rest of the process.
Then look in the MainMenu nib. Loading this is one of the first things the application will do. Any windows here that are set as “Visible on Launch” will come up immediately; more importantly, the application delegate will probably be here. Check the application's or File's Owner's (the application is both of them in this nib, so you need to check both) delegate outlet, and if one of them is connected, follow the connection. See what class that object is an instance of.
Once you've found the application delegate class, open it up in Xcode. Look through the list of application delegate methods and find which ones are implemented, and read the ones that are. The application:…FinishLaunching: twins will be particularly important at the start of the process.
From there, it's all just reading code, seeing what it does, and going where it takes you.
Peter's answers are good - I'd also say to check for implementations of 'awakeFromNib', especially for object loaded from MainMenu.nib. You often find interesting things stashed away in that method, rightly or wrongly.