【问题标题】:iOS: String value displaying as null while passing from one class to another?iOS:从一个类传递到另一个类时,字符串值显示为空?
【发布时间】:2025-12-17 15:40:01
【问题描述】:

我已经将一个 NSString 从一个类带到另一个类

我有一个测验视图控制器,用户在 UITextView 中输入一个问题,然后他们按下一步转到选择朋友视图控制器,在那里他们选择一个用户,然后通过 parse.com 发送问题

quiz.h

@property (nonatomic,strong) IBOutlet UITextView *textField;
@property (nonatomic, strong)  NSString *text;



quiz.m
- (IBAction)next:(id)sender {

NSString *text = self.textField.text;

if ([text length] == 0) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                            message:@"Enter some text"
                                                           delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alertView show];
    } else {
        selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
        sfvc.string = text;
    }

}



selectfriendsviewcontroller.h
@property (nonatomic, retain)  NSString *string;


selectfriendsviewcontroller.m

@synthezise string;
- (void)viewDidLoad {
[super viewDidLoad];

quizViewController *qvc = [[quizViewController alloc] init];
qvc.text = string;
UITextView *textfield = [[UITextView alloc] init];
string = textfield.text;
}

为什么字符串显示为空?在 quiz.m 中,当我按下 next 时,字符串传递为 null,关于如何修复的任何想法?

【问题讨论】:

  • 你在 viewDidLoad 中初始化了 UITextView。当时textView中没有文字。那你怎么能把 textfield.text 传给 string 呢?
  • 你也可以在 viewDidLoad 中分配 init quizViewController。并且当时 qvc.text 为空。
  • 感谢您的回复,我对 iOS 很陌生。我应该如何在 quiz.m 中分配和初始化一个 uitextview 来解决这个问题?在 IBAction 下?
  • 您正在将字符串从 quizViewController 传递给 selectfriendsviewcontroller 对吗?
  • 目前我仍在测试,但似乎仍然无法正常工作。 nsstring 不显示为空,但我上传到解析的文本文件是空白的。

标签: ios objective-c nsstring uitextview viewcontroller


【解决方案1】:

在 quizViewController 下的下一个按钮操作

- (IBAction)next:(id)sender {

    if ([text length] == 0) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error!"
                                                                message:@"Enter some text"
                                                               delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alertView show];
        } else {
            selectFriendsViewController *sfvc = [[selectFriendsViewController alloc] init];
            sfvc.string = self.textField.text;
        }
      }

然后在selectFriendsViewController.m中

- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"string %@",self.string);
}

还要检查textView的出口是否连接到UITextView。如果没有,则连接它。并选择FriendsViewController.h,创建属性@property (nonatomic, strong) NSString *string; 希望对你有帮助。

【讨论】:

    【解决方案2】:

    selectfriendsviewcontroller.m 您可以从 string 属性访问字符串的值(顺便避免像 string 这样的通用名称),如果您使用 Xcode > 4.4,您可以跳过 @synthezise

    selectfriendsviewcontroller.m

    -(void)viewDidLoad 
    {
      [super viewDidLoad];
      NSLog(@"%@",self.string);
    }
    

    【讨论】: