views:

34

answers:

1

Hi,

I have set up a delegate for my class 'HotRequest', but am having problems implementing it. The code for my class is below. Any ideas? Thanks

HotRequest.h

#import <Foundation/Foundation.h>

@protocol HotRequestDelegate;

@interface HotRequest : NSObject {
    NSString *requestString;
    id <HotRequestDelegate> delegate;
}

@property (nonatomic, retain) NSString *requestString;
@property (nonatomic, assign) id <HotRequestDelegate> delegate;

- (id)initWithRequestOptions:(NSDictionary*)dict;

@end

@protocol HotRequestDelegate <NSObject>
@required
- (void)requestComplete;
@end

HotRequest.m

#import "HotRequest.h"

@implementation HotRequest

@synthesize requestString, delegate;

- (id)initWithRequestOptions:(NSDictionary*)dict {
    if ((self = [super init])) {
        for (NSString *key in [dict allKeys]) {
            requestString = [NSString stringWithFormat:@"%@&%@=%@", requestString, key, [dict objectForKey:key]];
        }
        NSLog(@"%@", requestString);
    }
    [delegate requestComplete];
    return self;
}

@end

WelcomeViewController.h

#import <UIKit/UIKit.h>
#import "HotRequest.h"

@interface WelcomeViewController : UIViewController <HotRequestDelegate>{
     HotRequest *myRequest;
}

@property (nonatomic,retain) HotRequest *myRequest;

@end

WelcomeViewController.m

#import "WelcomeViewController.h"
#import "HotRequest.h"

@implementation WelcomeViewController
@synthesize myRequest;
- (void)viewDidLoad {
    [super viewDidLoad];
    NSDictionary *mydict = [[NSDictionary alloc] initWithObjectsAndKeys:@"2", @"1", @"4", @"3", nil];
    myRequest = [[HotRequest alloc] initWithRequestOptions:mydict];
    [[self myRequest] setDelegate:self];
}

- (void)requestComplete {
    NSLog(@"request complete");
}
@end
+3  A: 

delegate is still nil in initWithRequestOptions:. You are trying to call the delegate method before setting the delegate.

Ole Begemann
Not nil, actually - undefined, which is worse, since it will cause a crash.
Echelon
@Echelon: you are mistaken. On object allocation, all instance variables are zeroed out.
Ole Begemann
It's not undefined at all. -[NSObject alloc] zeroes memory, so you're guaranteed to have things initialized to 0/0.0/NO/nil/NULL/etc. Before anyone goes "But C doesn't guarantee that!", Objective-C requires that the underlying architecture is not "strange", e.g. sending a message to nil returns nil/NULL/0/0.0 despite the fact that objc_msgSend() doesn't know what return type you're especting (struct-returning methods are another story). If Apple ever ported Obj-C to a "strange" architecture, they'd probably tweak the ABI/compiler/runtime to preserve these guarantees.
tc.
I knew it had to be something stupid that I was doing. Thanks a lot.
Jack
@Ole Begemann - yes, of course, you're dead right - alloc ultimately calls calloc().
Echelon