Nav Link On

iPhone Dev Forums > General Development > SDK Coding Help > Delegate vs ViewController files/code ...

Reply

 

LinkBack Thread Tools Display Modes
Old 05-17-2009, 11:56 PM   #1 (permalink)
Member
Default Avatar
 
Join Date: May 2009
Location: Buffalo, NY area
Posts: 48
Default Delegate vs ViewController files/code ...

Can someone explain when you put code in one vs. the other?

I would assume if you are delegating, all the code would go there but I see examples where the code is split between the two.

Brooks
brimes is offline   Reply With Quote
Old 05-18-2009, 01:30 PM   #2 (permalink)
Administrator
 
MarkHernandez's Avatar
 
Join Date: Mar 2008
Location: San Diego, CA
Posts: 508
Default

Hi Brooks. Can you be more specific about what is confusing you? I was going to explain what delegates are but thought that would be overkill perhaps.

First of all, you are "delegated to" in your code, that is, you'll be responding to calls when the class is delegating to you. YOU won't be delegating to anything, just responding.

Is the whole delegation thing fuzzy to you? I know it took me a bit to understand it, but it's kinda simple. If you want I'll explain it.

And you said "the code is split between the two"... the two whats?

Mark
MarkHernandez is offline   Reply With Quote
Old 05-19-2009, 09:26 AM   #3 (permalink)
Member
Default Avatar
 
Join Date: May 2009
Location: Buffalo, NY area
Posts: 48
Default

I mean split between the .h and .m of the delegate files and the ViewController files. Below is the code from chpt 3 of Beginning iPhone Development. First are the .h and .m of the delegate files, then the .h and .m of the ViewController files.

So if there are delegate files, why are there classes in the ...ViewController.h and .m? Why isn't all the code in the delegate .h and .m?

If you are coding from scratch, how do you decide whether to have delegates or not? And whether to put code in the delegate files or the ViewController files?

Brooks
Code:

You must Login or Register to view and contribute code! This is done to increase participation in helping one another out, if you have been helped please pass on the favor.

//------------------------------------------------------------------------
//  Button_FunAppDelegate.h
//  Button Fun
//
//  Created by Jeff LaMarche on 6/13/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import <UIKit/UIKit.h>

@class Button_FunViewController;

@interface Button_FunAppDelegate : NSObject <UIApplicationDelegate> {
	IBOutlet UIWindow *window;
	IBOutlet Button_FunViewController *viewController;
}

@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) Button_FunViewController *viewController;

@end

//------------------------------------------------------------------------
//  Button_FunAppDelegate.m
//  Button Fun
//
//  Created by Jeff LaMarche on 6/13/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "Button_FunAppDelegate.h"
#import "Button_FunViewController.h"

@implementation Button_FunAppDelegate

@synthesize window;
@synthesize viewController;


- (void)applicationDidFinishLaunching:(UIApplication *)application {	
	
	// Override point for customization after app launch	
        [window addSubview:viewController.view];
	[window makeKeyAndVisible];
}


- (void)dealloc {
        [viewController release];
	[window release];
	[super dealloc];
}


@end

//=======================================
//  Button_FunViewController.h
//  Button Fun
//
//  Created by Jeff LaMarche on 6/13/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface Button_FunViewController : UIViewController 
{
	IBOutlet	UILabel		*statusText;
}
@property (retain, nonatomic) UILabel *statusText;

-(IBAction)buttonPressed:(id)sender;
@end


//------------------------------------------------------------------------
//  Button_FunViewController.m
//  Button Fun
//
//  Created by Jeff LaMarche on 6/13/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "Button_FunViewController.h"

@implementation Button_FunViewController

@synthesize statusText;

- (IBAction)buttonPressed:(id)sender
{
	NSString *title = [sender titleForState:UIControlStateNormal];
	NSString *newText = [[NSString alloc] initWithFormat:@"%@ button pressed.", title];
	statusText.text = newText;	
	[newText release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc {
	[statusText release];
	[super dealloc];
}

@end
brimes is offline   Reply With Quote
Old 05-20-2009, 01:13 AM   #4 (permalink)
Administrator
 
MarkHernandez's Avatar
 
Join Date: Mar 2008
Location: San Diego, CA
Posts: 508
Default

I'm going to take a stab at it for you. Read this and I'm pretty confident this will clarify and fill in the gaps for you, and I'm kinda explaining this for others as well.

But first, delete in your mind your existing notion of "delegate file" and let's start over.

Classes come first, and delegates follow them.

Let's start with the task of creating a new class. And when you do, you're subclassing a pre-existing one, right?

-------

My favorite way to explain how delegates work involves animals.

Let's say you are going to create a particular bird. You start with a predefined class definition of a bird (provided in the existing framework as, say, CFBird). The existing framework class assumes all birds have certain things in common -- they hatch and grow the same, poop the same, fly the same, and lay eggs the same way, etc. (tee hee, I said poop. ) But different birds look different, are different sizes, chirp differently, eat different things, and may mate differently.

So let's say Apple provided you with the basic bird class (with hatching, growing, pooping, flying and egg-laying behavior already built in).

Here now in this more advanced age of object-oriented design, there's a concept (design pattern) called "delegation" and it's a cool way to easily implement custom classes, assuming ahead of time that you'll likely never need to worry about anything else about creating birds other than specifying how they differ from each other -- how they look (size and color) and how they chirp, eat and mate.

So, the people who designed the CFBird class have set up a "protocol" which specifies the "delegate methods" (kinda like "callbacks" in C) which is all your new class will need to implement to create your custom bird, and you're done! Basically the class is going to call into your code when your particular bird is drawn, when it chirps, eats and mates. These tasks are "delegated" to you in your subclass of CFBird.

Everything else is handled for you, and you only need to concern yourself with what is different about your bird, and forget about what is the same amongst all birds, simplifying your life and making things more consistent.

In your code, when you specify your new class of bird, in the @implementation you'll make reference to a <protocol>, and by doing so you are telling the system that you agree to implement the methods specified in that protocol which will detail exactly how your particular bird is going to look, chirp, eat, and mate. Done and done.

The subclassing comes first, and the possible delegate methods follow if you specify a protocol to follow.

------

Now, for instance, say you want to implement a particular bird, say a "mockingbird." You subclass CFBird, and agree to implement the <CFBirdDelegate> protocol, and your class implements the predefined methods you just agreed to, called draw, chirp, eat and mate. In the "delegate" methods you write, you'll draw a medium sized bird with grey and white wings, and when the message comes and your object is asked to chirp your class will chirp mostly at night and change it's song constantly and be annoyingly loud, it will eat bugs, and when it goes to mate it will flap its wings and dance in a particular way.

Now let's say you want to implement a "yellowBelliedSapSucker." In a separate file in Xcode you'll subclass CFbird, and in your "delegate" methods in that .m file, you'll draw a medium sized bird with a yellow belly, and when it's asked to chirp your class will chirp briefly and only at sunrise, it will eat sap, and when it goes to mate it will do nothing in particular and you just let the default behavior stand.

Are you getting it?

------

Which delegate methods are each of these classes going to implement according to Apple's predefined <protocol> ?

Code:

You must Login or Register to view and contribute code! This is done to increase participation in helping one another out, if you have been helped please pass on the favor.

@interface MockingBird : CFBird <CFBirdDelegate> {
@interface YellowBelliedSapSucker : CFBird <CFBirdDelegate> {

- (void) draw {
- (void) eat {
- (void) chirp {
- (void) mate {



@interface MyAviaryAppDelegate : NSObject <UIApplicationDelegate> {

- (void) applicationDidFinishLaunching:(UIApplication *)application {    
- (void) dealloc {




@interface SamplePickerViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> {

// from the <UIPickerViewDelegate> protocol

- (NSInteger) numberOfComponentsInPickerView:(UIPickerView *)pickerView {
- (NSInteger) pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger) component {

// from the <UIPickerViewDataSource> protocol

-(NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
-(void) pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
-(CGFloat) pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {



// I'll let you go and see for yourself what these would be

@interface Simple_TableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
------

Understand that in Xcode, each class is usually in it's own separate file, and that's probably where the idea of "delegate file" is coming in for you. It's all the stuff between the @implementation and the @end.

But you don't have to figure out what to put where. It's predefined for you.

As you go along you'll see that the different types of things, like pickers, tables, etc will have a very particular set of delegate methods you need to implement and respond to.

Depending on what goes between the <protocol> brackets in the .h file, then that's the set of delegate methods you have to implement in the .m file of the same name.

Easy!!!!!

Hope this helps.

Mark
MarkHernandez is offline   Reply With Quote
Old 05-24-2009, 10:10 AM   #5 (permalink)
Member
Default Avatar
 
Join Date: May 2009
Location: Buffalo, NY area
Posts: 48
Default

Thanks for that thorough explanation, Mark!

I understand.

Brooks
brimes is offline   Reply With Quote
Old 06-14-2009, 08:30 PM   #6 (permalink)
Junior Member
Default Avatar
 
Join Date: Jun 2009
Posts: 1
Default

Thanks mark it was helpful to me as well! Thanks brimes for asking! delegates been confusing me for a long time
boobsy is offline   Reply With Quote
Old 06-20-2009, 04:06 PM   #7 (permalink)
Junior Member
Default Avatar
 
Join Date: Jun 2009
Posts: 1
Default

very nicely explained. I just started looking at the iphone dev docs and hoping to starting coding for iphone soon.
gogo is offline   Reply With Quote
Old 06-20-2009, 04:18 PM   #8 (permalink)
Junior Member
Default Avatar
 
Join Date: Jun 2009
Posts: 3
Default

The <blaDelegate> specifiers in Objective-C seem to work a lot like Interface class inheritance in Java or abstract classes in C++. The delegate definition says you will need 1 or more functions, and when you include that as part of your class, it's a promise to override those functions in your class. Apple often defines default implementations of these interface functions though, so you can override 1 out of 5 just to save effort, so it isn't purely abstract like Java or C++.

When Apple uses "delegate" as a noun, they are looking for the object that implements the functions they intend to call. In OO coding, practically everything is called with object.method, or [object method]. Since they let you override a lot of things, they will often let you set "object" by with the delegate: parameter, and the method will be overridden with the selector: parameter.

This is how you make things like UITimers call the function you want. Instead of the timer hardcoding in a certain object or method name, you pass the two things as parameters and it calls [delegate selector].

Hope that helps.
Vengeance is offline   Reply With Quote
Old 06-20-2009, 04:26 PM   #9 (permalink)
Junior Member
Default Avatar
 
Join Date: Jun 2009
Posts: 3
Default

Also, I meant to point out that most of the time your delegate functions probably make sense to be in your view controller subclasses. I'm still pretty new to Objective-C but it seems like that is where most of handling stuff ends up being.

In the MVC approach, you end up with objects with these basic responsibilities:

Model - Keeps app-specific data structures, loading/saving to database or file, etc.

View - Visualize data from the model. First responder to UI things like typing and clicking, although mostly these are passed immediately to the controller.

Controller - This ends up with most of the "what does the application do next" logic. Reacting to button clicks, flowing to the next window or back to the previous window, setting timers and catching them, etc.

In my code, my model classes are basic load/save/update stuff. The views have practically nothing in them, except a couple of custom drawRects. And the controllers have the other 80% of the intelligence.

I know it wasn't your actual question, but if you're new to this MVC model that Apple likes, perhaps this will be helpful.
Vengeance is offline   Reply With Quote
Reply

iPhone Dev Forums > General Development > SDK Coding Help


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


Powered by vBulletin® Version 3.8.4
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0 RC1