我尝试创建一个提醒用户将他们导入的歌曲命名为音乐表显示应用的提醒。
我为这个命名过程创建了一个函数:
- (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;
}
如何将警报中的selectedSongName分配到警报外的songName变量?
答案 0 :(得分:2)
将__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);