iPhone Objective-C Placement of NSNotifications - objective-c

I have a fairly complex iphone application that has many asynchronous processes occurring. To deal with this I'm making heavy use of NSNotification Center. My question is what is the "best practice", if such a thing exists", for registering the notifications? Right now they sprinkled through my code in a hap-hazard way. I'm about to go to production and I want it cleaned up. I though about having a "registerNotifications" method in viewDidLoad of the main view which obviously registers all notifications in one shot. Does this sound reasonable? If not what would be the preferred way of dealing with this. Thanks in advance for your help!!

Putting all the notifications in one object destroys encapsulation and that is bad. You make one objects notification operations dependent on another object working properly. It will actually be a nightmare tracking all that. It is also backwards to the entire of purpose of notifications which is to create a decentralized and modular messaging system.
Notifications shouldn't be "sprinkled throughout the code" but they should be managed solely by the objects that receive them. If you use a great deal of notifications you might need to create a class with dedicated methods for handling multiple notifications and then have your other classes inherit from that class. That way you get automatic management.
One of the big mistakes people make with notifications is that they register controllers when they really need to register their data model. For example, suppose you're downloading some data from a URL and you want to update the interface as it progresses and/or when it ends. If you have multiple views in your UI and you register controllers, then every view has to manage a notification (of which there may be more than one.) However, if you set up the shared datamodel to receive the notification you need only have a maximum of two notifications. One will go to the datamodel so the datamodel can update itself and then you can have the datamodel issue a generic notification for any listening views to update themselves from the datamodel.
Making your view controller dependent on the datamodel simplifies design greatly in all cases.

An object should register itself as an observer of the notifications it is interested in. The best time to do it is when the object becomes interested, otherwise you have to deal with notifications when you don't want them.

Related

Multiple ViewControllers - should I use a singleton object?

I have a new project, kind of a board game, and I'm using a storyboard which has multiple view controllers in it - the game simply moves from one view to the next with the player making various decisions and then loops back.
I have an object which holds information about the player (along with a couple of methods) - the score etc. I obviously only need one instance of this object and as I want each View Controller to access the same instance, should it be a singleton? I've never used them before and I've read they're often over-used, so I just want to check if this is the correct way to do this from the start. Many thanks.
What you have described is the Model for your application, holding the game data and core logic. Is there any reason to make this a singleton rather than passing it between your controllers?!
I would assume one controller calls the next and so can pass this information across?! We use singletons for services and the like but not for model data, it's not really the point of them in our experience.
I personally have nothing against singletons, as long as you don't use too many of them in one project. While other people might recommend you use some other mediation for this project, I say go for it—this is exactly what you'd use a singleton for.
Singleton's can be be bad if you are developing a library component, a large server project, or for unit testing. But since you are doing an iphone game don't fret about it, it'll will be easier and faster just to use a singleton.
If you are worried about unit testing, since objetive-c is latebound and singletons are made with factory methods instead of constructors it's not hard to changeout the singleton for your unit test anyway.

iOS Pass messages between views, window based app

So i'm working on an iPad window based app at the moment. There will be a number of views where I will want to pass some simple data between, mainly strings (id's) to tell the next view what to load.
Just wondering how to go about this? I've come across this < http://idisk.mac.com/DChampney-Public/ViewControllerDataSharing.zip > solution which seems like the best but I am caught for time and it might be a little overkill for me at the moment.
Would it be ok to create a string in the appdelegate where I can store the id to be read by the next view?
Any ideas welcome..
Thanks.
Define properties on your View Controllers for passing objects around (such as NSManagedObjectContext in all the Core Data samples & templates)
Make one view controller the delegate of another, for passing data as the result of an event (such as selecting a tableview row, this is how UITableViewDelegate works)
Use a publish/subscribe pattern for synchronous notifications between objects, through NSNotificationCenter. This should really only be used where more than one object might publish or subscribe, or where the connection between objects is distant (several view controllers between them). For async pub/sub use NSNotificationQueue
Do not use AppDelegate as the bag-of-data for your application. It's painful to change, bad design, and hard to read.

Organizing iOS project for MVC design pattern

I'm working on a multiview app for iPhone and currently have my views (VIEW) set up and their transitions (CONTROLLER?) working nicely. Now I'd like to add objects for the actual program data (MODEL).
My question is: How should I structure my data to adhere to the Model View Controller (MVC) design pattern? I know I should create separate classes to implement my data structures and that my controller classes can pass messages to them from the view, but are there any other organizational considerations I should examine? Especially those particular to Cocoa Touch, Xcode, or iOS?
Other particulars: Playback of pre-recorded and perhaps user-generated audio will also be essential. I know these are model elements, but how exactly they relate to the "V" and the "C" I'm still a bit fuzzy on. I suppose when a user action requires audio playback, the CONTROLLER should pass a message to the MODEL to ready the appropriate sounds, but where exactly should regulation of the playback live? In a "PlayerController" separate from the ViewController I imagine?
Many thanks and pardon my MVC noobery.
Caleb gives a good introduction and overview of how to think about the problem. In your particular case, here are some of the pieces you would might have given your description:
Clip (M) - Responsible for holding the actual audio data. It would know how to interpret the data and given information about it, but it wouldn't actually play anything.
Player (V) - Actually plays a clip on the speakers. Yes, that's a kind of view in MVC. Audio is just another kind of presentation. That said, you'd never call it "PlayerView" because that would suggest it were a subclass of UIView.
PlayerView (V) - A screen representation of the Player. Knows nothing about Clips.
ClipManager (C) - An object that would keep track of all the clips in the system and manage fetching them from the network, adding and removing them to caches, etc.
PlayerViewController (C) - Retrieves a Clip from the ClipManager, and coordinates a Player and a PlayerView to display and play it, as well as any other UI elements (like a "back button" or the like).
This is just an example of how you might break it down for some theoretical audio player app. There are many correct MVC ways to do it, but this is one way to think about it.
Lord John Worfin (and, I'm sure, someone before him) said: "Character is what you are in the dark." Well, a model is what an application is when nobody is looking -- it's the data and logic that defines how the app behaves regardless of how it's presented on screen.
Imagine that you decide to add a command-line interface to your application. You'd still want to use the same structures for managing your data, and your logic for sorting, sifting, and calculating based on the data should still be the same too. The code in your app that remains important/useful no matter how the user sees or interacts with the app is the model.
A model can be very simple and made up entirely of standard objects. iOS apps are often more about retrieving, storing, and displaying data than they are about crunching numbers, so it's not unusual to have a model that's just an array of dictionaries, or a hierarchy of dictionaries that's several levels deep. If you look at Core Data's NSManagedObject class, it's similar in many respects to NSMutableDictionary. So, don't be afraid to use standard objects if they're appropriate.
That said, you can certainly also create your own model objects, and that's useful if you have certain requirements that you want to enforce on your data, or if you want to be able to derive information from the data.
Beginners often wonder how each controller gets access to the model. Some folks advocate using the singleton pattern for this, mainly because it provides a single, shared, globally accessible object. I don't recommend this. Instead, have some high-level object in your app such as the app delegate create/load the model (which will likely be a graph of many individual objects) and give a pointer to the model to any view controllers that need it. If those controllers in turn create other view controllers, they can again provide a pointer to the model (or part of it) to their child controllers.
I hope that helps.

How do I share CLLocation throughout my app?

I'm developing an app which has several view controllers which make use of the users current location. Since the users current location should be the same no matter which view I'm in, I think it makes sense to share this location between view controllers. Should I define a CLLocation in my Application Delegate and then set each view controllers usersCurrentLocation to match this? When the location is updated by one view controller, how do I ensure each of the other view controllers pick up the change? To me this sounds like a job for a global variable, but I know they're not a very 'Cocoa' way of doing things. What's the correct way to do this? Code samples would be helpful.
Singletons are a perfectly Cocoa way of doing things, and a "Location Manager" singleton (or whatever you choose to call it) instantiated upon app launch can not only provide the information to anything that needs the information, but can also periodically check for a location change and send notifications to any listeners.
Matt Gallagher does a great job of explaining singletons on his blog, and includes a super-handy macro for doing the heavy lifting.
Instead of assigning a location as property, consider a CCLocationManager as property. Same amount of work and keeps itself up to date... Whenever you need the current location, just send it the location message.
It's a philosophical question. If it's only a little data, then yeah, a named property in your app delegate is a fine way to handle it. Especially if it's a property of the app (like where it's running physically). I don't mind.
More data than that, and I prefer to create a singleton data manager class, so it can be gotten to globally but has its own namespace.
If I were you, I would have all your location management code live in the app delegate itself, and think of individual viewcontrollers as "clients" of the delegate's location manager, picking up the current state from the delegate's .currentLocation (or whatever) property as needed.
If you can handle some iffy accuracy from time to time, you might also consider using the "updates on significant change" mode of CLLocationManager, rather than real live GPS tracking.

Implementing Model-View-Controller the right way

Working on a game in Objective-C/Cocoa for OS X, and I finished the prototype as much as it's worth being finished. It's a mess of code, being my first game, but everything works. I've been reading up on the best way to put things together, and MVC seems to make the most sense, but I'm a bit confused.
Where does it start? With the controller? That seems to make the most sense to me, but how is it started? In my mess of a prototype, I have everything starting from the init of the view and going from there. Would I just do the same for the controller, and put what's needed in the init? Or is there something else I can use to do this? If it's started from the init, how do I init the controller?
How would I set up the game world? I currently use two arrays, one for the world (Walls, Floors, Doors, Water, Lava, etc.), and one for the items (I'll be adding a third for characters). The map (a .plist) is loaded, and then the objects are created and added to the array it belongs to. Where do the arrays go? In the prototype, they're also part of the view, so I guess you could say I combined the two (View and Controller) together. Would there be a Map object created for each map? Would there be a Maps object that contains all of the maps?
How does it all work together? The player presses a key, which moves the character in the game. The view would be handling the input, right? Would you send that to the controller, which would check for everything (walls, monsters, etc) in the map/other arrays, and then return the result? Or would you send it to the player, which would go to the controller, which would do all of the the checks, and then return the result?
I thought I had it pretty nicely laid out in my head, but the more I think about it, the less solid my ideas become and the more confused I get. By all means do not hesitate to draw something up if you think it will get the point across more efficiently.
If you've taken the time to read all of this, thank you for your patience. From what I've gathered, most people that write code don't use any sort of design. After reading up on this, I can see why some people would avoid it, it's confusing and people seem to think it isn't worth the time. I personally think that the advantages totally outnumber the disadvantages (are there any?) and it only makes sense to keep things organized in a way that you won't have to do a total rewrite every time you want to implement a new feature. You wouldn't build a house, car, or an appliance without a design, why would you write a complex program without one?
I asked this question because I want to do it the right way, instead of hacking and half-assing my way to "victory".
You may be interested in a presentation I gave to ACCU '09 - "Adopting Model-View-Controller in Cocoa and Objective-C".
Where does it start? With the
controller? That seems to make the
most sense to me, but how is it
started?
Create a new Cocoa app project and you'll see that there's already a controller class provided by the template - it's the app delegate class. Now look in MainMenu.xib. There's an instance of the app delegate, and it's connected to the "File's Owner" object's delegate outlet. In this case the NSApplication is the File's Owner; it's the thing that wanted MainMenu to be unpacked. So this really is the delegate of the application.
That means we've got something which is a controller object, can talk to the NSApplication instance, and can have outlets to all the other objects in the XIB. That makes it a great place to set up the initial state of the application - i.e. to be the "entry point" for your app. In fact the entry point should be the -applicationDidFinishLaunching: method. That's called once the application has finished all of the stuff needed to get your app into a stable, running state - in other words Cocoa is happy that it's done what it needs to and everything else is up to you.
-applicationDidFinishLaunching: is the place where you want to create or restore the initial Model, which is the representation of the application's state (you could also think of it as representing the user's document, if that analogy is suitable for your app - document-based apps are only a little more complex than the default) and tell the View how to represent things to the user. In many apps you don't need to load the whole Model when the app has launched; for a start it can be slow and use more memory than you need, and secondly the first View probably doesn't display every single bit about the Model. So you just load the bits you need in order to show the user what's up; you're Controlling the interaction between the View and the Model.
If you need to display other information in a different View - for example if your main View is a master view and you need to show a detail editor - then when the user tells you what they want to do you need to set that up. They tell you by performing some action, which you could handle in the app delegate. You then create a new Controller to back the new View, and tell it where to get the Model information it needs. You could hold the other View objects in a separate XIB, so they're only loaded when they're needed.
How would I set up the game world? I
currently use two arrays, one for the
world (Walls, Floors, Doors, Water,
Lava, etc.), and one for the items
(I'll be adding a third for
characters). The map (a .plist) is
loaded, and then the objects are
created and added to the array it
belongs to. Where do the arrays go? In
the prototype, they're also part of
the view, so I guess you could say I
combined the two (View and Controller)
together. Would there be a Map object
created for each map? Would there be a
Maps object that contains all of the
maps?
We can work out what objects we're modeling by analysing your statement above - you may not realise it, but you've sketched out a specification :-). There's a world which contains walls, doors etc., so we know we need objects for those, and that they should belong to a World object. But we also have items and characters - how do they interact with a world? Can a place contain water and a character? If so, perhaps the world is made up of Locations, and each Location can have a wall or a door or whatever, and it can also have items and characters. Note that if I write it like this, it seems that the item belongs to the location, not the location to the item. I would say "the mat has a cat on it" rather than "the cat has a mat underneath it".
So simply think about what you want your game world to represent, and the relationships between the things in the game. This is called domain modeling, because you're describing the things in the game world rather than trying to describe things in the software world. If it helps, write down a few sentences describing the game world, and look for the verbs and nouns like I did in the last paragraph.
Now some of your nouns will become objects in the software, some will become attributes of other objects. The verbs will be actions (i.e. methods). But either way, it will be easier to think about if you consider what you're trying to model first, instead of jumping straight down to the software.
How does it all work together? The
player presses a key, which moves the
character in the game. The view would
be handling the input, right? Would
you send that to the controller, which
would check for everything (walls,
monsters, etc) in the map/other
arrays, and then return the result? Or
would you send it to the player, which
would go to the controller, which
would do all of the the checks, and
then return the result?
I like to follow the "tell, don't ask" policy, which says that you command an object to do something rather than asking it to give you the information to make the decision. That way, if the behaviour changes, you only need to modify the object being told. What this means for your example is that the View handles a keypress event (it does because they're handled by NSControl), and it tells the Controller that this event occurred. Let's say the View receives a "left arrow" keypress, and the Controller decides this means the player should move left. I would just tell the player "move left", and let the player sort out what happens when moving left means bumping into the wall or a monster.
To explain why I want to do it that way around, imagine that you add in game 1.1 the ability for the player to swim. Now the player has some ableToSwim property, so you need to change the player. If you're telling the player to move left, then you update the player to know what moving left over water means depending on whether they can swim. If instead the Controller asks the player about moving left and makes the decision, then the Controller needs to know to ask about being able to swim, and needs to know what it means near water. As does any other controller object in the game that might interact with a player, as does the controller in game for iPhone ;-).
It seems like your main confusion is how things are constructed during app start up. A lot of people get stuck on this, because it feels like something magic is going on, but let me see if I can break it down.
App is launched by user
C main() function is called
main() calls NSApplicationMain()
NSApplicationMain() load the MainMenu.nib (or another nib specified in the info.plist)
Nib loading initializes all of the objects defined in the nib (including the application delegate)
Nib loading makes all the connections defined in the nib
Nib loading calls awakeFromNib on all the objects it just created
-applicationWillFinishLaunching: is called in the application delegate.
NSApplication (or a subclass specified in the Info.plist) is initialized
-applicationDidFinishLaunching: is called in the application delegate.
Note that the application delegate is initialized BEFORE the NSApplication (sub)class. That is why application(Will|Did)FinishLaunching: takes a notification as opposed to the NSApplication it is a delegate of.
The general consequence of this is that your views are created for you via nibs, and you controllers are created as a side effect of nib launching since they tend to either be root level objects in the nibs, or the nib's File's Owners. Your model is usually created either in the application delegate or as a singleton that is lazily initialized when something first access it.
You should create a model for the the whole game. It should contain everything about the game except the GUI interaction. The views, on the other side, contain all GUI stuff without knowing anything about the game flow.
The whole point is that models and views are expected to be reusable. The model classes should play with any GUI (and maybe even the console or command line). The view classes should be able to be used with other similar-looking games. Models and views should be completely decoupled.
Then, the controller fills the gap. It reacts on user input, asks the model classes to perform a specific game move, and asks the views to show the new situation. The controller is not expected to be reusable. It's the glue which holds the game together. The controller ensures that model classes and view classes remain indenpendent and reusable.
In addition, don't try to make the design perfect from the start. Don't hesitate to refactor at any time. The faster a bad design decision gets corrected, the less evil it does. Designing everything upfront means that a bad design decisions won't be corrected at all, unless you make a perfect design upfront, which is simply improssible even with decades of experience.
Always remember the third design rule of the X Window System: "The only thing worse than generalizing from one example is generalizing from no examples at all."
For your game the model would include things like the current position of the character, the number of health points, and other values that involve the "state" of the game. It would notify the view whenever something changed so that the view could update itself. The view would simply be the code required to show everything to the user. The controller is responsible for responding to user input, and updating the model when necessary.
The controller is the central component in this, and it is what should instantiate the model and view.
When the player presses a key, the view should simply pass that command onto the controller, which decides what to do.
You are wrong that most people don't design. Perhaps most amateurs, or perhaps the people who ask the most questions online, but not anyone working on a project that is even somewhat sophisticated. Professional programmers are all experienced in software design; without it they literally would not be able to do their job (write software to do X).
Your game sounds like it is complicated enough to warrant an architecture pattern like MVC. There are some instances where a piece of software is simple enough that MVC is overkill and needlessly complicates things, but the threshold for using MVC is pretty low.
You might find this article Introduction to MVC design using C# useful. Although the example is in C#, the principle should apply.