I am a newbie to iPhone development and have some basic questions to ask about protocols and delegates. I have two view controllers: view controller and viewcontroller2nd. I have UITextField in one of them and would like to type something (like a name) in it and in the viewcontroller2nd, I have a UILabel and i would like it to appear Hello, name when the UITextField is changed.
I am following this video: http://www.youtube.com/watch?v=odk-rr_mzUo to get the basic delegate to work in a single view controller.
I am using protocols to implement this:
SampleDelegate.h
#import <Foundation/Foundation.h>
@protocol ProcessDelegate <UITextFieldDelegate>
@optional
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
@end
@interface SampleDelegate : NSObject
{
id <ProcessDelegate> delegate;
}
@property (retain) id delegate;
@end
SampleDelegate.m
#import "SampleDelegate.h"
@implementation SampleDelegate
@synthesize delegate;
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
lbl.text = [NSString stringWithFormat:@"Hello, %@",txtField.text];
[txtField resignFirstResponder];
}
@end
ViewController.h
#import <UIKit/UIKit.h>
#import "SampleDelegate.h"
@interface ViewController : UIViewController <ProcessDelegate>
{
IBOutlet UITextField *txtField;
}
@end
Viewcontroller.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
ViewController2nd.h
#import <UIKit/UIKit.h>
@interface ViewController2nd : UIViewController <ProcessDelegate> {
IBOutlet UILabel *lbl;
}
@end
and ViewController2nd.m is standard code from Xcode.
My question is how do i link my delegate function to my viewcontroller and viewcontroller2nd to get it working?
Pardon me if the question is stupid.. Need some guidance. Do point me any other mistakes that i am doing as well.. Thanks..
Your delegation is a bit… Off.
Firstly: Don’t override UIKit delegate methods through protocol inheritance. It’s pointless. Why not just make your class conform to the specified delegate in the first place?
Secondly: When an object has defined a protocol, a valid instance of that object must be in use by its delegate (or at least passed to it). So, anything that wants to be the delegate of
SampleDelegate(really a bad name for a class, by the way) would initialize a validSampleDelegateobject, and call-setDelegate:as though it were any other property.Thirdly: You don’t actually define any delegate methods! What’s the point of delegation if there’s nothing to delegate!l
Fourth, and most important: Never, ever, ever, ever use the
retain, orstrongstorage specifiers with a delegate! Delegate objects are supposed to beweakorassignto prevent nasty retain cycles.