传递时显示为null&从其他类中获取数据

时间:2016-11-14 08:19:46

标签: ios objective-c class uiviewcontroller

有两个类DropDownPickereditAddVehicle类。我只是在editAddVehicle中声明了一个名为“brandID1”的字符串变量,我希望它能从DropDownPicker Class中提取数据。

这是我的代码:

DropDownPicker.h

@property(nonatomic,retain) NSArray *selectedIndex; 

DropDownPicker.m

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

   if ([[dataArrayForPicker objectAtIndex:row] isKindOfClass:[NSString class]]){
      NSLog(@"Selected %@. Index is: %i brand id %@" , [dataArrayForPicker objectAtIndex:row], row,_selectedIndex[row]);
      editAddVehicle *controller=[[editAddVehicle alloc]init];
      controller.brandID1=_selectedIndex[row];
      NSLog(@"Brand Id %@",controller.brandID1);
      // Brand Id 50
      self->pickerTextFeild.text = [dataArrayForPicker objectAtIndex:row];
   }
   else 
      self->pickerTextFeild.text = [dataArrayForPicker objectAtIndex:row];
}

DropDownPicker到这行代码controller.brandID1=_selectedIndex[row];,我很容易在crandID1中存储字符串,但为什么它仍然在editAddVehicle.m显示为空?

EditAddVehicle.h

@interface editAddVehicle : UIViewController
@property(nonatomic,retain)NSString *brandID1;
@end

EditAddVehicle.m

@interface editAddVehicle()<UITextFieldDelegate>
{
    NSString *brandID1;  
}
@end

@implementation editAddVehicle
@synthesize brandID1;
{
    UITextField *textFeild1=(UITextField *)[self.view viewWithTag:10];
    brand= [[DropDownPicker alloc]initWithTextFeild:textFeild1 withData:brandArray];
    [brand setPlaceHolder:@"Brand"];
    brand.selectedIndex=brandCode;
    [brand addTarget:self action:@selector(brandSelected:) forControlEvents:UIControlEventValueChanged];
}

-(void)brandSelected:(DropDownPicker *)sender{
    NSLog(@"%@",brandID1);
    // (null) why ?
}

1 个答案:

答案 0 :(得分:1)

将错误的方法传递给用户委托或NSNotificationCenter以传递数据。

此处为NSNotificationCenter的我的示例

//在DropDownPicker中

   - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
    {
    if ([[dataArrayForPicker objectAtIndex:row] isKindOfClass:[NSString class]]){
       NSLog(@"Selected %@. Index is: %i brand id %@" , [dataArrayForPicker objectAtIndex:row], row,_selectedIndex[row]);
       [[NSNotificationCenter defaultCenter]postNotificationName:@"NotificationForData" object:_selectedIndex[row]];

    }
        else{ 
self->pickerTextFeild.text = [dataArrayForPicker objectAtIndex:row];
// un comment if you want pass data here
// [[NSNotificationCenter defaultCenter]postNotificationName:@"NotificationForData" object:_selectedIndex[row]];
        }

}

IN editAddVehicle     //在viewdidload中

 [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(brandSelected:) name:@"NotificationForData" object:nil];

-(void)brandSelected:(NSNotification*)noti{
    NSString *brandID1 = [noti object];
    NSLog(@"%@",brandID1);
}