如何使用Protocols objective-c [英] How to use Protocols objective-c

查看:68
本文介绍了如何使用Protocols objective-c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将Picker选择的值继承到另一个地方。我正在尝试下面的代码但是null值即将到来..请检查我哪里出错了。
我必须继承在 PickerView 中传递的字符串值..请检查代码

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];
}


推荐答案

您正在打印出一个值在你设置它之前的代理...所以它将打印null。你应该在调用didFinishPicking方法时打印出你的字符串,因为这是你设置字符串的地方。

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);
}

注意一方:避免任何名称惯例使用诸如Activity_1,Picker1之类的数字,这是非常糟糕的代码练习。

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

这篇关于如何使用Protocols objective-c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆