remote xml file and uinavigationcontroller, nsurlconnection placement - iphone

Firstly, I studied apple's sample codes : SeismicXML and TopSongs but both of them and other tutorials generally calls NSURLConnection in app delegate.
In my ugly project, I have to call NSURLConnection after user reach some viewcontroller in uinavigationcontroller.
So, I'm asking this design issue, Should I still keep NSURLConnection methods in app delegate, and calling from my internet aware vc or completely move this NSURLConnection methods and delegates to my internet aware vc ?
Also, there is another design issues which mess my head since I'm not even starter :)
I have to keep the number of view uitableview which is constructed from xml, and its
detailed view. Therefore, I think that I must two request to my web service. One to getting xml file and the other one must be made in detailed view to increase view count of related data in web service.
But, I think that it's not a good solution, Is there any library or any other approach to keep this list and its detailed view counts and notify my server?

The way I do it is make a separate class that I use only for connection calls and methods, instantiate it from the delegate, set that instance from the delegate as a property (or manually create its setters and getters) and use in in any class/controller I want to.
This way you modularize your application and the classes don't get tangled up and it's easier to debug/follow the flow of the application.

Related

Need of Delegation in iPhone Development or Objective C

What is the need of delegation in iphone/ipad development or objective C?
I read so many articles on it. All were telling how to implement the concept, but no one was telling why we need to implement that, in which case we should implement it.
Suppose you want to implement Login functionality in your app ... now you won't show Login screen every time you run your app.. only when it is first started and you don't have a login and password...
So in this case..
Your app starts :
View 1 loads (default view )
You check no Login name is there..
You load a new view..(Login View ) .
User enter his details..you get your login and password...
now you want to go back to default view and load the main app with
the names the user entered in Login View....
Now you will use delegate to pass these information(login details) back to default View..so that it knows..its details. now there are many different ways to do these things...like notification and singleton classes.. but when you want to sent more than 3-4 sets of data.. it is best to use delegates
Think of all the components that iOS and Cocoa provide you with. TableViews, TextFields, PopOvers...etc.
When the developers wrote these components, they couldn't possibly know all the various implementations that us developers were going to create using these components. But we need somehow to communicate with them in a generic way.
These components use delegates. The delegate is an implementation independent way of describing some behaviour that your component can conform to.
When UITableView need to find out what is the height of the rows, the UITableView only needs to know about UITableViewDelegate. It doesn't need to know about MyTableViewController, JohnsTableViewController, BobsTableViewController... etc.
So the delegate is decoupling the component from the implementation and the type.
Decoupling is a good thing. It makes maintaing and changing code a lot easier, and makes code reusable.
Delegation is a simple and powerful pattern in which one object in a
program acts on behalf of, or in coordination with, another object.
The delegating object keeps a reference to the other object—the
delegate—and at the appropriate time sends a message to it. The
message informs the delegate of an event that the delegating object is
about to handle or has just handled. The delegate may respond to the
message by updating the appearance or state of itself or other objects
in the application, and in some cases it can return a value that
affects how an impending event is handled. The main value of
delegation is that it allows you to easily customize the behavior of
several objects in one central object.
SOURCE
Use a delegate if you want to talk to only one object. For example, a
tableView has a delegate - only one object should be responsible for
dealing with it.
Use notifications if you want to tell everyone that something has
happened. For example in low memory situations a notification is sent
telling your app that there has been a memory warning. Because lots of
objects in your app might want to lower their memory usage it's a
notification.
this was an answer posted to my question here
There are two key benefits of delegation: customizing objects without subclassing, and improving encapsulation.
Customization without subclassing is a benefit you get from many of the Cocoa and Cocoa-Touch APIs using the delegate pattern. If they didn't do so, you might have to subclass a UITableView every time you wanted to change its behavior by using different types of cells or a different data source. Instead, you just set the table view's delegate and data source to customize its behavior.
As for encapsulation, the delegate pattern helps you keep the different components of your code separate. For example, if your custom View needs to have some data, it would be bad practice to simply give it access to your Model, or even full access to your Controller. Instead, you'd probably set up some kind of delegate protocol for your View that your Controller would implement. That way your classes know no more about each other than they need to, so that changes in one part would be less likely to break others.

iOS AsyncSocket in Views or Delegate

I got a connection if I use the AsyncSocket in the AppDelegate. Is it possible to define sockets in views? Because the method to call is named initWithDelegate. I only need the connection in some views. I also need this connection in a thread as aditional class. Can I pass the connection via Constructor?
You can. But you should probably add the socket as a property of a singleton class. That way, you would have access to from from wherever it is needed.
Putting networking code in a view smells wrong to me. Your views should handle display and user interaction, and should generally be agnostic as to where the data comes from or goes to. That's the job of the controller layer.
I'm not saying that it's inconceivable that you might have networking code in a view (UIWebView comes to mind, but that is almost certainly implemented internally as a collection of classes, including controllers, and just presents itself as a UIView), but you should have a very good reason why that makes the most sense.
By using a controller you reduce the chance you will paint yourself into a corner down the road.

Changing Background Image for Mainview

I am fairly new to Objective-C, but haven't been able to find the answer I am looking for yet.
I am building a practice app which counts down days till specific events (christmas). It all works well, but I wanted to implement a simple way to change the background image (created from storyboards). The current setup of the app is a basic utility app, with the alternate view containing a UISegmentedControl that will set which background image will be displayed behind the countdown label.
I know I can just push separate views, but that seems quite inefficient. I am fairly sure I can use NSNotifications to update the background image, but am still unclear after reading the documentation how to implement it.
One way is to use delegates. A delegate is a callback. That avoids one view passing a reference to another view and having it poke (introduces coupling). Instead, one provides a callback via a formal protocol and delegate to the other.
Here's an SO question that covers it:
What exactly does delegate do in xcode ios project?
Another option is to have a shared model. Using a singleton pattern, multiple views can share a model (data and operations) and you can use NSNotificationCenter to send notifications. When the other view gets the notification that the background changed, it can query the model and update the background.
Related posts:
Giving notification to another class with NSNotificationCenter
How to share an object with the entire project?
As far as the pros and cons go, basically a notification is good when you want to broadcast a change to multiple views. Delegation is good when two items need to communicate directly with some abstraction.
NSNotificationCenter vs delegation( using protocols )?

good examples of model-view-controller

I'm new to Objective-C and the iPhone and thought I was getting the hang of it until, after many play apps, I ran into a really basic problem around MVCs, NIBs and IB. Are there any really clear explained examples of how to follow this framework that I could go back to?
#interface test1ViewController : UIViewController {
IBOutlet myView *myview;
IBOutlet myModel *mymodel;
}
Both the views and models are linked in by IBOutlets but instantiating the model object either kills the application or produces an object which does not respond to any messages.
I am also unclear as to where to carry best out initialisations. I currently do this over viewDidLoad in the view controller. Is there a standard way to do this and does the simulator actually always start up in the same way? Should one use awakeFromNib? Does it make any difference if I use plain code or the IB? And if I have use the IB, should it include a model object?
The MVC idea would make good sense for me here because I have potentially several views and view controllers all feeding back into - and sharing - one common central data model. Any references or advance on this newbie problem would be more than welcome!
I wouldn't spend too much time worrying about the 'classic' definition of MVC. iOS follows it, but there's a lot of confusing terminology. ("View Controller")
You say trying to use model kills your app. Are you retaining myModel? You have to retain all IBOutlets.
nibs are collections of "Freeze-Dried" objects. When you load a nib, the objects in it are "rehydrated", if you will. This means they spring back to life with all of their properties set to whatever they were when you froze them. So you talk of "instantiating" and "initializing" but this does not apply to IB. The objects are ALREADY instantiated and initialized. Imagine that compiling the nib 'pauses' the objects. When you load the nib, the objects resume doing whatever they were doing when frozen. They will get an awakeFromNib message, so that's a good place to put some code to check on what the state of the app is, see if you have to do stuff with your object to bring it up to speed.
viewDidLoad seems like an "initialization" method but don't be fooled. It's part of the view controller life cycle and it can be called more than once! (If your controller's view is purged as part of a low memory warning, viewDidLoad might be called again if the view has to be... wait for it... reloaded.) So, it's appropriate to put view setup stuff in viewDidLoad, but not other initialization type things.
For the "common data" thing, I like to create a singleton data model class. Your various views can set properties on the model, or send notifications. You can also use KVO (key value observing) to watch for changes in the model.
IB makes functionality invisible. I don't like it and I don't use IB any more, preferring to have everything in code. Then when you look at code you see what is going on - all the navigation controllers, all the formatters etc. - without switching over to IB. Maybe Xcode4 will make it better with integrated IB but I probably won't go back. Lots of people do like IB so try both methods and see what you like best.
IBOutlet/IBAction actually mean nothing to the compiler but they let IB recognise the ivars it can send messages to or that will write to elements in a xib. Your use of it here is a bit simplistic unless you really do have a model that only communicates one way with the xib. What you more usually have is a range of controls in the xib linked to the view object, the view communicating directly with the controller. The controller communicates with the model. Very loosely speaking, model is your internal representation of data and logic, view is what you see, controller is the glue between them.
The MVC line can be fuzzy and you just have to get comfortable with it. If you have a slider control with a value representing some value in your model then it can be hard to think of it as part of the interface especially when you persist the value and use it as a central part of your model. I like the Stanford iPhone class introduction of it. They don't spend a heap of time on it because it can be difficult to follow exactly and there are situations where it isn't best.
Notes from that class - you can find the video on iTunes to follow along.
Your use of viewDidLoad is correct, that's your chance to perform initialization on views and their objects. If using IB you will probably not have much to do there because you can set most properties in the xib. If not using IB you will use it a lot more.
A lot of times something like your model would be wired at runtime by your application delegate or by the view controller itself.
IB is generally used more to link views and controllers together, with the application handing around model(s).
That said, you should be able to have IB create an instance of your model and assign it in an IBOutlet. Was your model OK with just being created without the classic init method being called? Did it implement NSCoding properly?

NSNotification vs. Delegate Protocols?

I have an iPhone application which basically is getting information from an API (in XML, but maybe JSON eventually). The result objects are typically displayed in view controllers (tables mainly).
Here is the architecture right now.
I have NSOperation classes which fetch the different objects from the remote server. Each of these NSOperation classes, will take a custom delegate method which will fire back the resulting objects as they are parsed, and then finally a method when no more results are available. So, the protocol for the delegates will be something like:
(void) ObjectTypeResult:(ObjectType *)result;
(void) ObjectTypeNoMoreResults;
I think the solution works well, but I do end up with a bunch of delegate protocols around and then my view controllers have to implement all these delegate methods. I don't think its that bad, but I'm always on the lookout for a better design.
So, I'm thinking about using NSNotifications to remove the use of the delegates. I could include the object in the userInfo part of the notification and just post objects as received, and then a final event when no more are available. Then I could just have one method in each view controller to receive all the data, even when using multiple objects in one controller.†
So, can someone share with me some pros/cons of each approach. Should I consider refactoring my code to use Events rather then the delegates? Is one better then the other in certain situations? In my scenario I'm really not looking to receive notifications in multiple places, so maybe the protocol based delegates are the way to go.
Thanks!
Actually, your design sounds sound. The clear Cocoa approach is using delegates, and is much preferred to throwing objects around. Also, defining your protocols this way makes your code very explicit and easy to understand. All in all: keep up the good work