-1

I have a quiz.vc and i am passing an NSString from on vc to another and it passes null. (i am using a UITextView)

Quiz.h
@property (nonatomic,strong) IBOutlet UITextView *textField;
@property (nonatomic, retain) NSString *userText;

Quiz.m
- (IBAction)next:(id)sender {
    // i have tried NSString *userText also and passing in userText to sfvc.string
    self.userText = self.textField.text;

            selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
            sfvc.string = self.userText;
}



selectFriendsViewController.h
@property (nonatomic, strong)  NSString *string;

selectFriendsViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@", _string);
}

its always logging null at runtime? i have tried so many ways and methods! any ideas as to how i can pass a string and not null???

Thanks

Harry
  • 17
  • 6

3 Answers3

1

Your error

  selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
  sfvc.string = self.userText;

This create a new instance of selectFriendsViewController,but you do not use it.It will be dealloced when the method is done.So,you got nothing.

If you fire a segue in the IBAction,use prepareForSegue to pass data.

Edit, If you fire a segue when the button clicked.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.destinationViewController isKindOfClass:[selectFriendsViewController class]]) {
    selectFriendsViewController * dvc = (selectFriendsViewController*)segue.destinationViewController;
    dvc.string = self.textField.text;
}
}
Leo
  • 24,596
  • 11
  • 71
  • 92
0

I think u can't navigate and push the value to next viewController use this code if you using xib files.

- (IBAction)next:(id)sender {
    selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
    sfvc.string = self.textField.text;

[self.navigationController pushViewController:sfvc animated:YES];

}

hope that code helps you.

Tapas_ios
  • 73
  • 6
0

If you don't want to show null,use the below code

  #pragma mark - check string is empty or not

   - (IBAction)next:(id)sender 
    {

        self.userText = self.textField.text;
        selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
        sfvc.string = [self checkEmpty:self.userText];
    }

  - (void)checkEmpty:(NSString *)check
   {
     @try 
     {
       if (check.length==0)
         check = @" ";
       if([check isEqual:[NSNull null]])
         check = @" ";
     }
     @catch (NSException *exception) 
     {
       check = @" ";
     }
   }
user3182143
  • 9,459
  • 3
  • 32
  • 39