Override Interface Builder instantiation of objects? - objective-c

I'm developing for the iPhone, and I have a class DataManager, that is used to maintain my application data. When the application launches/exits, the data is read from/written to disk to create an instance of this class, using the NSKeyedArchiver (and Unarchiver) classes, since the DataManager adheres to the NSCoding protocol.
One problem I'm having is that I need the DataManager to be accessible by many of my other IB classes, so it is defined as an object in IB, and those classes have an outlet to it. The DataManager is being created using the standard init: method (or maybe initWithCoder:?), but since IB doesn't have the proper file (or NSData from the file) to instantiate the object, it has no initial contents.
So, is there any way to tell IB not to instantiate the class automatically? This will instead be performed using my application delegate, something like:
AppDelegate.h
IBOutlet DataContext *context;
AppDelegate.m
context = [NSKeyedUnarchiver unarchiveObjectWithData:dataLoadedFromFile];
As you can see, this presents a problem. Wouldn't the context be instantiated twice, once by InterfaceBuilder, then a second time by my application delegate?
I would like to prevent maintaining the context as an ivar in the delegate, since that seems to stray from the MVC paradigm, and leans toward the singleton pattern instead. (The controller should not be responsible for the data in my mind. It can maintain a reference to it obviously, but should not be responsible for offering it to other classes.)

When the application launches/exits, the data is read from/written to disk to create an instance of this class, using the NSKeyedArchiver (and Unarchiver) classes, since the DataManager adheres to the NSCoding protocol.
One problem I'm having is that I need the DataManager to be accessible by many of my other IB classes, so it is defined as an object in IB … As you can see, this presents a problem. Wouldn't the context be instantiated twice, once by InterfaceBuilder, then a second time by my application delegate?
Yup.
First, you should think about whether this is a controller or a model object. It sounds to me like it's a controller.
If it is, then you should move the model to a separate object or objects, and make those NSCoding-compliant, and make the data manager load and save those objects. A bonus of this solution is that you could tell the data manager to save the objects and purge them when you get a low-memory warning, not just at quit time.

Related

In Objective-C, the rule that designated initializer always get called is not always obeyed?

Can we rely on the fact that in Objective-C, the rule is that a class's designated initializer is always called for sure? Or can we say, it should be almost always true, except a couple of exceptions? For example, for UIView, the docs says:
initWithFrame:
If you create a view object programmatically, this method is the
designated initializer for the UIView class. Subclasses can override
this method to perform any custom initialization but must call super
at the beginning of their implementation.
If you use Interface Builder
to design your interface, this method is not called when your view
objects are subsequently loaded from the nib file. Objects in a nib
file are reconstituted and then initialized using their initWithCoder:
method
Or can we say that, if it is programmatically, the rule should always apply for well designed classes, but Interface Builder is a bit different because it sort of "revive" or build the object from a non-programmatic way. If so, are they other exceptions in general when we do iOS programming?
The fact is that class designed with Interface Builder are unarchived and not initialized .
Being archived involves that the class is not initialized but unarchived, so the initWithCoder: method takes responsibility for setting up the control when it's loaded using the archived attributes configured by Interface Builder.
You should put your initialization operations in the awakeFromNib: method that gets called in each case after the object is loaded, thus you will be sure that your initialization statements will be called .

iOS - Outlets in Category implementation files

Overview
I have a iOS project in which the view controller implementation which has become large and thought it would be better to break into categories based on the functionality
The outlets in the view controller implementation file are not available in the category's implementation file.
Note - I am using ARC (automatic reference counting)
Question
I have an outlet to the textfield created in my view controller's implementation file. Now can I create another outlet to the same text field in my view controller category's implementation file ?
Would it cause any memory not be released or any other memory issues (Both the outlets are going to be weak and non atomic) ?
Is this acceptable from a design perspective or is there a better way to do it ?
Can category's methods be accessed in view controller's implementation ? I can include the header file but I want to know if at runtime there would be any unpredictable behavior
If you need to access declared IBOutlet properties in the categories of your view controller class, why not declare them in the class header file so that they are available to your categories? The ability to declare properties and ivars in implementation files now is meant to hide messy details of your implementation, but not at the risk of making your code unmanageable. Your functional design seems sensible.
You can have as many outlets as you want, they are pointers that will allow you to modify the object trough them.
If you are using arc and assuming you used the Interface Builder to create your text field then no, since you set them to weak it just means that these pointers wont count towards the retain count of the object, so the object will be kept alive as long as at least 1 strong pointer points to it. in this case the Interface builder's view is retaining it, when that view is deallocated so will the object be. Being non atomic means that its not tread safe but this doesn't matter for your purpose.
It really depends on your program, since i cant picture it with your description i can only advice into trying to stick to the MVC model when developing on iOS.
https://developer.apple.com/library/ios/#documentation/General/Conceptual/CocoaEncyclopedia/Model-View-Controller/Model-View-Controller.html

Execute NSFetchRequest on application startup

In another question ( Accessing an NSApplications delegate in another class? ) I asked about calling the Application's delegate because I needed it's managedObjectContext for a fetch request. However, when I try to let all values be displayed in an NSTableView on application startup, I'm running into problems. DataController, my NSTableViewDataSource, calls it's init-method before my application delegate calls it's applicationWillFinishStartup or any other method to initialize the managedObjectContext. What am I doing wrong? How else can I fill an NSTableView with already existing objects?
You should access managedObjectContext only via its getter, even from DataController, as in [appDelegate managedObjectContext] or appDelegate.managedObjectContext.
Your managedObjectContext method should automatically set up the managed object context; you shouldn't write an explicit moc setup routines in your applicationDidFinishLaunching, etc. And the standard core-data template is written that way.
Now, for this to work, the app delegate needs to be properly set up from the point of view of DataController. However, init is called before all the IBOutlet is set up, so that's the wrong place to perform setup operations of objects inside the nib. Instead, use awakeFromNib to do these things. awakeFromNib is sent to every object after the IBOutlet etc. are all set up.
That said, writing your own DataController is a total waste of time. Just instantiate the standard NSArrayController in the nib file, and use it in the Core Data mode via binding. There's absolutely no need for you to write the fetch request by yourself. Study Apple's own CoreData sample codes and then google "Binding CoreData Tutorial" for many tutorials available on-line.

Using Protocols in Objective C to Transfer Data Between Different Objects?

Hey guys, I currently have a root table view which has a toolbar at the bottom and has labels and a refresh button within it, much like the Mail app's toolbar. This root table view controller obtains data from a server by allocating and initializing a DataUpdater class. Within this class are the NSURLConnection delegate methods that are called while communicating with the server.
As you can probably guess, I need to know when certain (delegate) functions are called within the DataUpdater class and the values of the parameters passed to these delegate functions so that I can update the labels on the toolbar accordingly (i.e. Connecting..., Updated, etc).
The problem I am having is determining how to notify the root table view controller of what is going on in these delegate methods. Would I use protocols, if so how? I have been skimming the documentation and don't quite see how I would get this effect. Or would you suggest I implement my program another way?
Thanks in advance!
A protocol is a kind of contract that says: I promise to provide the non-optional methods defined in the protocol, and maybe even the optional ones. It's purpose is like Java interfaces: to work around missing multiple-inheritence.
The delegate pattern in Objective-C normally works like this: you define a protocol, and then in your class, you define a variable like id<MyProtocol> myDelegate; and define a setter and maybe getter (either via normal methods, e.g. - (void)setDelegate:(id<MyProtocol>)aDelegate; or via properties.
Note that the delegate is not retained ! So if you work with a property, you need the assign option, not retain.
Now back in your class, you check whether myDelegate is nil and if not, you can directly call its non-optional methods. If you want to call an optional method, you first need to verify its presence via respondsToSelector:.
So if you decide to use the delegate pattern, you need to define a protocol, add that protocol to your root table view controller, implement the necessary methods there, and make sure to call [foo setDelegate:self]; or something similar to inform your other class that the root table view controller is the delegate. And of course implement the delegate calls in your class.
Edit:
An alternative might be to use NSNotifications, BTW. The advantage of notifications is that you can have multiple objects listen and react to them. The disadvantage is that you cannot (directly) pass values back. For example, you can define a delegate method that asks the delegate whether to do something or not. That's not possible with notifications, it's more like shouting into a room instead of having a one-to-one conversation.
DarkDust's answer about protocols is fine but I would like to add some things to it.
One underlying thing that is often forgotten when it comes to delegation is object ownership. When a program is running it creates a tree of objects. Its root object is the application delegate and for example it owns a navigation controller, which owns the individual view controllers, which own the view and the view owns its subviews and so on.
Often the question comes up: "Why is the delegate not retained, just assigned?" The problem is that if you send a message to a deallocated object the program crashes. So how do you make sure the delegate stays around? The answer is object ownership.
I give you an example: a UITableView and its data source which is the TableViewController which is nothing but a delegate. The TableViewController holds a reference with its view property to the UITableView, so it owns the TableView. That means when the tableView is alive there must also be its parent object present, which is the UITableView's delegate. So there is no danger that the delegate goes away somehow.
In the end it is again all about memory management.
Take home message is: think upfront about object ownership will make your program mode modular, easier to maintain and will lead to a looser coupling between individual objects.

Connecting delegate classes in Objective-C

I've got two controls in my Interface Builder file, and each of those controls I've created a separate delegate class for in code (Control1Delegate and Control2Delegate). I created two "Objects" in interface builder, made them of that type, and connected the controls to them as delegates. The delegates work just fine. My problem is, I need to share information from one delegate to the other delegate, and I'm not sure how.
What is the best way to do this? Combine the two delegates into one class, or somehow access a third class that they can both read? Since I'm not actually initializing the class anywhere in my code, I'm not sure how to get a reference to the actual instance of it (if there is an actual instance of it), or even access the "main" class that the project came with.
You can add outlets from either delegate to the other delegate. There are two ways to add an outlet to an object in IB (assuming you're using Xcode/IB version 3.0 or later:
If you have not generated the code for your delegate classes yet, select the desired delegate, then open the "Object Identity" tab in the IB inspector. Add a "Class outlet" of type NSObject. You should then be able to set this new outlet to the other delegate. Of course you will have to generate the code for your delegate class and add the generated source files to your Xcode project before you can load the nib.
If you've already generated the code for the delegate class (or added an NSObject to your NIB and set its Class to an existing class in your Xcode project), add an instance variable to the delegate class:
IBOutlet id outletToOtherDelegate;
As long as your Xcode project is open (as indicated by the green bubble in the lower-left of your NIB window), IB will automatically detect the new outlet and allow you to assign it to the other delegate object in your NIB.
Cocoa automatically connects these outlets at NIB load time. Once awakeFromNib is called on instances of your delegate objects, you may assume that all the other objects in the NIB have been instantiated and all outlets have been connected. You should not assume an order on calls to awakeFromNib, however.
I think you can create outlets on each one and cross-bind them so that they each have the same data all the time. If there's one model object they need to share, that's pretty tidy. I don't actually know how to do this; I think I saw it in an iPhone tutorial one time!
I don't have my Mac in front of me currently since I'm at work, but would it be possible to bind an instance of one delegate to a member of the other delegate? This would be similar to binding an NSArrayController to a member of another controller class, for example.
However, depending on what the delegate classes are doing, if the tasks are similar I would probably just combine them into once class. That would eliminate the problem altogether.