简体   繁体   English

如何使用协议Objective-C

[英]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. 我需要将Picker选择的值继承到其他地方。我正在尝试下面的代码,但空值来了..请检查我要去哪里。 I have to Inherit String values that is been passes in the PickerView ..please check the code 我必须继承在PickerView传递的String值。请检查代码

Picker1.h Picker1.h

#import <UIKit/UIKit.h>

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

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

picker.m 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 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 活动_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];
}

You are printing out a value of a delegate just before you are setting it up....so it will print null. 您将在设置它之前打印出委托的值。...因此它将打印null。 You should print out your string when the didFinishPicking method is called instead since this is where you are setting up your string. 您应该在调用didFinishPicking方法时打印出您的字符串,因为这是您设置字符串的地方。

-(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. 请注意一侧:避免使用任何带有数字的名称约定,例如Activity_1,Picker1,这是非常糟糕的代码习惯。

You are NSLogging delegate before creating self.delegate1 itself Please use the below lines of code. 在创建self.delegate1本身之前,您是NSLogging委托。请使用以下代码行。

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

And put NSLog inside "didFinishPicking" 并将NSLog放入“ didFinishPicking”

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM