I am fairly new at programming (I have no education in programming – everything I know have been obtained by reading tutorials) and completely new at XCode and iOS developing. So far I understand the basics in developing an iOS app, but one thing I can’t figure out how works is delegates. I understand the idea behind using delegates, but I don’t know what I am doing wrong when trying to implement delegates. I have created a small example (Single-view application) to illustrate how I am implementing a custom delegate and I hope you can tell me what I am doing wrong.
I am using XCode 4.5.2, iOS6.0 with ARC enabled.
In the example I create a simple NSObject subclass (TestClassWithDelegate). TestClassWithDelegate.h looks like this:
@protocol TestDelegate <NSObject>
-(void)stringToWrite:(NSString *)aString;
@end
@interface TestClassWithDelegate : NSObject
@property (weak, nonatomic) id<TestDelegate> delegate;
-(TestClassWithDelegate *)initWithString:(NSString *)theString;
@end
TestClassWithDelegate.m looks like this:
#import "TestClassWithDelegate.h"
@implementation TestClassWithDelegate
@synthesize delegate;
-(TestClassWithDelegate *)initWithString:(NSString *)theString
{
self=[super init];
[delegate stringToWrite:theString];
return self;
}
@end
The view controller (ViewController) consists of a UILabel which I want to write some text to.
ViewController.h looks like this:
#import "TestClassWithDelegate.h"
@interface ViewController : UIViewController <TestDelegate>
@property (weak, nonatomic) IBOutlet UILabel *testlabel;
@end
ViewController.m looks like this:
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize testlabel;
- (void)viewDidLoad
{
[super viewDidLoad];
self.testlabel.text = @"Before delegate";
TestClassWithDelegate *dummy = [[TestClassWithDelegate alloc] initWithString:@"AfterDelegate"]; //This should init the TestClassWithDelegate which should "trigger" the stringToWrite method.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark Test delegate
- (void)stringToWrite:(NSString *)aString
{
self.testlabel.text = aString;
}
@end
Problem with above example is that the label on the view only writes “Before delegate” where I want it to write “AfterDelegate”.
All help is much appreciated. Happy New Year.
You haven’t set the delegate anywhere, so it will be
nil. You’d either need toinitWithString:delegate:instead ofinitWithString:or (better) just create the object, set the delegate, and send the string separately.You may have made a (common) mistake whereby you assume that
@synthesizeactually creates an object within your code and assigns a value to it. It does not. It is a (now mostly redundant!) instruction to the compiler to create accessor methods for a property.Below is a slightly reworked example of your delegate class, and some example usage:
.h file:
.m file:
Usage: