[英]How to use Protocols objective-c
我需要將Picker選擇的值繼承到其他地方。我正在嘗試下面的代碼,但空值來了..請檢查我要去哪里。 我必須繼承在PickerView
傳遞的String值。請檢查代碼
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
活動_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方法時打印出您的字符串,因為這是您設置字符串的地方。
-(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,這是非常糟糕的代碼習慣。
在創建self.delegate1本身之前,您是NSLogging委托。請使用以下代碼行。
delegate1 = [[Picker1 alloc] init];
[delegate1 setDelegate : self];
並將NSLog放入“ didFinishPicking”
-(void)didFinishPicking:(NSString *)pickedStr
{
NSLog(@"pickedStr%@", pickedStr);
[self setStr:pickedStr];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.