ios - 访问在 alertController 中声明的变量

标签 ios objective-c

我正在尝试创建一个提醒,提示用户为他们导入到乐谱显示应用程序中的歌曲命名。

我已经为这个命名过程创建了一个函数:

- (NSString *)nameImportedSong {
    NSString *songName;

    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"New Song"
                                                                              message: @"Choose a song name"
                                                                       preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.placeholder = @"song name";
        textField.textColor = [UIColor blueColor];
        textField.clearButtonMode = UITextFieldViewModeWhileEditing;
        textField.borderStyle = UITextBorderStyleRoundedRect;
    }];
    [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        NSArray * textfields = alertController.textFields;
        UITextField * namefield = textfields[0];
        NSString *chosenSongName = [NSString stringWithFormat:@"%@", namefield.text];

    }]];

    songName = ; // <-------------how do I assign chosenSongName to songName?

    [self presentViewController:alertController animated:YES completion:nil];

    return songName;

}

如何在警报之外将警报中的 chosenSongName 分配给我的 songName 变量?

最佳答案

为变量使用__block关键字

__block NSString *chosenSongName;

 [alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
    NSArray * textfields = alertController.textFields;
    UITextField * namefield = textfields[0];
    chosenSongName = [NSString stringWithFormat:@"%@", namefield.text];

}]];

songName = chosenSongName;
NSLog(@"chosenSongName = %@",chosenSongName);

关于ios - 访问在 alertController 中声明的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44510275/

相关文章:

ios - 如何为 sprite kit 实现触摸和按住?

ios - 如何将 UI 元素放入 TableView 中

objective-c - 对象分配初始化不规则

objective-c - NSMutableData 不自动释放内存

ios - 在方法之间传递数组中的数据

ios - 带有 UIProgressView 的自定义 UICollectionViewCell 在重用单元上显示 ProgressView

ios - 'UIPopoverController' 已弃用 : first deprecated in iOS 9. 0

ios - 如何通过数组访问.csv文件目录

iphone - 我何时以及为何需要释放对象?

ios - 没有找到目标的伞形 header ,将不会生成模块映射