Delegate And Observer Design for Updating Data throughout an App - objective-c

I'm building an iPhone app that has a central class, M, that gets a bunch of data from a Web API. Whenever this class gets data, it has to update two controllers, say A and B. To support this both A and B are listed under an interface that has an update command. A and B also need to be able to query data from class M, so I've added a handle to M in both A and B.
The problem is that is setup isn't very modular. I'm looking for ways to clean up the design.
EDIT - Also, class M doesn't have any preconceived notion of what the exact type of the class A and B will be.
Thanks.

Just do as you're proposing on the title: use the observer pattern. A and B are observers (that implement an observer protocol) to M, which is the subject. When you update the observers, also provide the event data through the update method, maybe as a handle to a subject protocol that M implements. This way, A and B are decoupled from M through the observer and subject protocols.

Related

General OO design pattern

Consider the following general program structure:
Class A has an instance of Class B as a member variable
Class B has a collection member variable containing instances of class C
Events in class A are propagated to the C instances by A simply telling B about the event
What are the design patterns concerning instances of class C talking back to class A?
One option is instances of class C posting notifications to which class A subscribes. Another option is passing a reference to class A "down the chain" (from A to B then from B to each C). This latter option allows instances of C to talk directly to A.
If you mean design patterns literally (i.e. of the GoF variety) then these would be a few relevant options:
Command: pass a callback to the C items (directly or indirectly through B) so that when they want to talk back to A they can simply invoke this callback -- which can even have parameters
Iterator: B exposes a view of its aggregate collection directly to A; communication between A and C is then made directly
Mediator: Exposes notifications to which A and C might subscribe to; communication is done by posting events
Observer: What you already suggested as the first option
If on the other hand you really mean architectural patterns, then typical options are:
Your first option, A subscribing to C events. At first sight this doesn't look like an all-around good idea unless the event is extremely useful all the time, because it requires n objects to aggregate a pointer back to the callback which in the worst case they could even use just once.
Passing references to A is another option, but not a good one if you are going to pollute the public interface of A with methods just so that C can call back to it in very specific scenarios. It can be very effective if A already exposes a suitable interface, but be aware that you might need an adapter class between C calling back to A in order to not tightly couple C to A's interface.
A third option would be A iterating over (a view of) the collection provided by B directly and supplying callbacks to C instances; this has the advantages of being quite loosely coupled and that it will use the least amount of memory, but it might be a bit trickier to code.

Best way to determine the behavior of a view's containing view

My situation:
ClassA may or may not have a parent of type ClassB. Therefore saying [instanceOfA.superview somethingClassBSpecific]; is half hazardous. Plus, Xocde will get pissy, for good reason.
Is the recommendation here to dispatch a notification, or do some logic on the superview, e.g.,
if([objectOfA.superview respondsToSelector:somethingClassBSpecific] != nil){
//...
}
Or create a delegate of type ClassB where the situation permits?
As is so often the case, it depends. Using the view hierarchy, notifications, and delegation are three different ways that objects can communicate with each other. Deciding which of those (if any) is most appropriate requires thinking about how the objects in question are related to each other.
Notifications provide very loose (nearly zero) coupling between objects. They also provide one-to-many communication -- you post a notification, and every object that's listening for that notification will get the message. But notifications aren't always appropriate; communication is mainly in one direction only, and abusing the notification mechanism can lead to performance problems.
Delegation gives you a way to customize the behavior of an object. The most obvious example is the application delegate. Most every iOS application is based on the same class: UIApplication. UIApplication is exactly the same for every app even though each app does its own thing. The application object uses a delegate to provide the customization that gives the application its unique behavior.
The view hierarchy is another way that (some) objects are connected to each other. If the behavior you're implementing is a) part of a view and b) dependent on that view's relationship with other views, then it may make sense to use the superview and subviews properties.
So, what kind of functionality are you trying to implement?
This depends on your logical model. If you have an instance of a class implementing a protocol with optional methods, then using respondsToSelector: is appropriate when you are trying to call one of these optional methods. If you want the method you call to be required, create a do-nothing "guard" in the classes that you pass. Both techniques are valid, it's only a matter of whether or not you'd like your users to be conscious of the need to implement a specific method.

xCode / Objective-C Anatomy Analogies - Help a Noob Get It

OK so I'm trying to get started with Xcode and I have some experience with OOP in general but mostly I'm used to scripting. Anyhoo, I'm trying to get a handle on some concepts in objective C and xcode and I'm having some problems putting everything together.
For starters, I'm having trouble understanding what delegates and protocols do. I think it would be useful if someone could explain this with a simple analogy of a postman, or a teacher, or a factory or something. I don't understand the difference between a method in a delegate and a regular class methods.
Say I have a Class Postman. Now postman has methods sortMail() and deleteMail(). What's an example of a delegate method. And if a delegate is used, where is the data returned? Inside the delegate? Do I have to instantiate the delegate and then read results from it or does the delegate kinda give the results back to the calling object? Where do protocols come in...
Simple examples please :) Baby steps.
Protocols and Delegates go together frequently. It helps to understand what a protocol is first.
Protocol
A protocol is a way of having a class promise to implement a standard set of methods.
Example: A certified electrician has a certain set of skills that all certified electricians will have. If you need someone to do something that a certified electrician is certified to do, then any certified electrician should be able to do it (in theory at least).
Delegate
Now a delegate is an object that has been given a responsibility to fulfill certain requirements. One object can be given the responsibility of fulfilling a need of another object.
Example: When building a house, the house needs to have wires run etc. This responsibility has been given to a certified electrician, and we know he can do it because he's certified (i.e. implements a certain protocol).
Putting it all together in a Cocoa context:
A UITableView needs cells supplied so it can display them. To supply the cells, a class will need to be created (or at least specified) which implements the UITableViewDataSource protocol. That guarantees that the class does the needed things to supply the UITableView with the needed cells.
So the UITableView delegates the responsibility of providing the cells to a certain class object which implements the protocol which guarantees that the object knows how to supply the needed cells.
Example
A delegate is an object that handles particular functionality for another object - as in "Object A delegates certain functionality to object B".
For instance, you may use an instance of Apple's class NSURLConnection to make a request for a web service, but Apple's code obviously won't know what to do with the data it downloads, so you provide a delegate object to handle that functionality. NSURLConnection then delegates that functionality to your object by passing it messages when it needs to do something like handle the data it downloads.
Another example is a table view. Apple have written a lot of code to display table views and handle interactions with them, but it doesn't know what data you want to display or what needs to be done with that data when somebody interacts with it. So you can provide delegate objects for these things. When a table view needs to know what data to display, it asks your delegate to fetch the data for it. When the user selects an item, it asks your delegate to handle it.
A protocol is simply a way of describing what messages the delegate is supposed to understand. There can be informal protocols, where it's just described in the documentation, and formal protocols, which are defined in a header file.

How to access a class from another class?

I’m fairly new to OO. If I have two classes A and B that need to exchange data, or call each other’s methods, I need to be able to access an instance of class B from class A. Should I maintain the address of the instance object in a global variable? Should I appoint a (singleton) master class, and make (pointers to) instances of A and B properties of the master class? (AppDelegate comes to mind.)
Is there a straightforward by-the-book way to implement this? Somehow I‘m missing some "best practice" here. I’ve looked through Apple's examples, but didn't find an answer.
EDIT: Since I'm fairly new to MVC design patterns, my question is essentially "Who creates who"?
We're talking about an Audio Player here. 1. When the user selects a song, the UI displays its waveform by creating a viewController which creates the appropriate view. 2. When the user hits play, the UI displays a timeline while the song is playing by overlaying a new view over the waveform. Now, the latter view needs some info from the waveform display viewController. Right now, I'm storing a pointer to the viewController in an instance variable of my appDelegate. This works, but feels extremely strange.
Should I outsource the info that is needed by both classes to some third entity that every class can access easily?
Classes aren't simply departments of code. They are templates for the creation of objects, which you should think of as actors in your program, doing things within their areas of responsibility (which you define—you decide what each object does) and interacting with each other.
While you can handle a class as you would an object, classes generally do not talk to each other. Most of the time, you will create and use instances of the classes—which is what we normally mean by “objects”—and have those talking to each other. One object sends another a message, telling the receiver to do something or changing one of the receiver's properties. These messages are the interactions between your program's objects.
Those weird expressions in the square brackets are message expressions. Nearly everything you'll do with a class or object will involve one or more messages. You can send messages to classes the same as to objects, and classes can send messages just as objects can.
In Cocoa and Cocoa Touch, you typically have model objects, view objects, controller objects, data objects (such as NSString, NS/UIImage, and NSURL), and helper objects (such as NSFileManager). The classes you'll write for your application will mainly be model, view, and controller objects (MVC). The model represents (models) what the user will see themselves manipulating; the view displays the model to the user; the controller implements logic and makes sure the model gets saved to and loaded from persistent storage.
For more information, see Object-Oriented Programming in Objective-C and the Cocoa Fundamentals Guide.
Since I'm fairly new to MVC design patterns, my question is essentially "Who creates who"?
Controllers create and load the model, and load the views, and pass the model to the view for display. Certain controllers may also create other controllers.
It's good to keep a straightforward tree-like graph of ownership from a single root of your program—typically the application object—down through controllers to leaf objects in the models and views. If two objects own each other, that's a problem. If an object is not owned by anything outside of its own class (a singleton), that's usually a problem as well—a sign you need to think some more about where that code belongs. (Helper objects are the main exception; most of those are singletons. Again, see NSFileManager for an example. But they are few and far between.)
Further situation analysis require more information. At first place you should more specify the relation between classes and what exactly do you mean by exchanging data.
Singletons should be generally avoided. If you want to exchange information it is usually sufficient to provide for example instance of the class A to the instance of the class B by some method or constructor. The instance of B is then capable of calling public methods (and accessing public properties) of the instance of A.
A little bit of "best practices" can be learn by searching up "Design Patterns".
You should decide if one class can be an object of another class (encapsulation), or if one class can inherit from the other class (inheritance). If neither of these is an option, then maybe you could make one class (or some of its members) static?
Thanks for your contributions. Additionally, I found information on this page very useful. It lays out MCV considerations for cocoa in a hands-on way and practical language.

Core Data - Managed object question

I have 2 basic questions regarding Core Data;
What exactly is a managed object -- Is it equivalent to 1 instance of a class. For example, if there is an entity called Shape which has attributes like no of sides & color and if there are 5 entries displayed in a table, does it mean there are 5 managed objects each with attributes no. of sides & color. I am a bit confused about this basic concept.
What exactly is the relationship between Fetched Results Controller (FRC) and a table view? I know the delegate methods, but how exactly is the table view impacted/related to FRC ?
Any basic examples will be really useful. Thank you.
Q1. A managed object is a representation of some entity that has been persisted by an application. It is simply a generic abstraction away from the actual persisted type. So you are right in saying that the managed object will have the same keys/properties as the concrete type. As the NSManagedbject class implements the key-value coding pattern you can query its key/values at runtime...
- (id)valueForKey:(NSString *)key
For full documentation on NSManagedObject see here
Q2. The fetched results controller is what your UIViewController is to your UIView. It contains the logic that controls persistence for your table view. Its sole purpose in life is to keep database handling logic out of your UITableView. It does so by allowing you to define the behaviour you want to execute in the context of your UITableView. What I mean by this is that its delegate provides methods with signatures that explicitly imply an effect on a UITableView.
Q1. Yes, there are 5 managed objects out there and available to you. You could put all five in an array if you wanted to. Managed Object is simply a term that means you have code to manage the Insert, Change, and Delete actions into the database - in otherwords, some code manages it through its life cycle. You get at it through an FRC, the FRC ^fetches^ instances of the object from the database, and allows your code to ^control^ what happens to the ^result^. Hence the name.