Christien
Christien

Reputation: 1213

How to use Protocols objective-c

I need to inherit Picker selected values into the other place .I am trying the below code but null value is coming ..please check where I am going wrong. I have to Inherit String values that is been passes in the PickerView..please check the code

Picker1.h

#import <UIKit/UIKit.h>

@protocol pickerDelegate <NSObject>
-(void)didFinishPicking:(NSString *)pickedStr;

@end
@interface
@property(nonatomic,retain)id<pickerDelegate>delegate;

picker.m

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {


 string=[NSString stringWithFormat:@"%@",[list objectAtIndex:row]];

 label.text=string;

 [self.delegate didFinishPicking:string];


}


- (void)viewDidLoad
 {
[super viewDidLoad];


list =[[NSMutableArray alloc]init];
[list addObject:@"a"];
[list addObject:@"b"];    

}

Acitivity_1.h

 #import <UIKit/UIKit.h>
#import "Picker1.h"
@interface Activity_1 : UIViewController<UIApplicationDelegate, pickerDelegate>{

@property(nonatomic,retain)Picker1 *delegate1;
@property (nonatomic,retain)NSString *str;

@end

Activity_1.m

- (void)viewDidLoad
{
[super viewDidLoad];
 **this is how i print the value but value is null**
 NSLog(@"delegate1%@",self.delegate1.string);


delegate1 = [[Picker1 alloc] init];

[delegate1 setDelegate : self];


}

-(void)didFinishPicking:(NSString *)pickedStr
{
[self setStr:pickedStr];
}

Upvotes: 0

Views: 626

Answers (2)

tiguero
tiguero

Reputation: 11537

You are printing out a value of a delegate just before you are setting it up....so it will print null. You should print out your string when the didFinishPicking method is called instead since this is where you are setting up your string.

-(void)didFinishPicking:(NSString *)pickedStr
{
    [self setStr:pickedStr];

    // print the string you have just picked here if you want
    NSLog(@"Picked string: %@",pickedStr);
}

Note one the side: avoid any name convention with number such as Activity_1, Picker1 this is extremely bad code practice.

Upvotes: 1

Paramasivan Samuttiram
Paramasivan Samuttiram

Reputation: 3738

You are NSLogging delegate before creating self.delegate1 itself Please use the below lines of code.

delegate1 = [[Picker1 alloc] init];
[delegate1 setDelegate : self]; 

And put NSLog inside "didFinishPicking"

-(void)didFinishPicking:(NSString *)pickedStr
{
 NSLog(@"pickedStr%@", pickedStr);
 [self setStr:pickedStr];
}

Upvotes: 0

Related Questions