Ios 将UIAlert文本字段保存到核心数据

Ios 将UIAlert文本字段保存到核心数据,ios,objective-c,core-data,uitextfield,uialertview,Ios,Objective C,Core Data,Uitextfield,Uialertview,所以我有一个UIAlertView,它有两个按钮和一个文本字段,我的问题是我想将用户在文本字段中输入的文本保存到核心数据中的字符串“name”中。我所有的核心数据编程都是正确的,我将其用于UITextField,而不是alertview上的。我只是不知道如何保存用户在UIAlertView的文本字段中输入的内容。如果有人能帮助我,我将不胜感激 以下是我的警报视图的外观: UIAlertView的我的代码: - (IBAction)button:(id)sender { Lists *li

所以我有一个UIAlertView,它有两个按钮和一个文本字段,我的问题是我想将用户在文本字段中输入的文本保存到核心数据中的字符串“name”中。我所有的核心数据编程都是正确的,我将其用于UITextField,而不是alertview上的。我只是不知道如何保存用户在UIAlertView的文本字段中输入的内容。如果有人能帮助我,我将不胜感激

以下是我的警报视图的外观:

UIAlertView的我的代码:

- (IBAction)button:(id)sender {
    Lists *lists = [NSEntityDescription insertNewObjectForEntityForName:@"Lists" inManagedObjectContext:_managedObjectContext];

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Add List" message:@"Create a New Wish List" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Save", nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    [alert setTag:2];
    [alert show];

    NSError *error = nil;
    if (![_managedObjectContext save:&error]) {
        //Handle
    }

您需要使用
UIAlertViewDelegate
从警报视图中的UITextField捕获用户输入

让我们告诉UIAlertView您将使用委托,如下所示:

UIAlertView *alert = ...; 
//other UIAlertView settings here 
alert.delegate = self;
接下来,在代码中实现以下委托方法:

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
{
    if ([buttonIndex != 0 && alertView.tag == 2) {
          NSString *name = [alertView textFieldAtIndex:0].text;
    }
}
当然,为了调用委托方法,还需要符合头文件中的委托:

@interface CustomViewController : UIViewController <UIAlertViewDelegate>  
@接口CustomViewController:UIViewController

调用委托方法时,需要从文本字段中提取字符串

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

UITextField *tf = [alertView textFieldAtIndex:0];

Lists *lists = [NSEntityDescription insertNewObjectForEntityForName:@"Lists" inManagedObjectContext:_managedObjectContext];

lists.name =tf.text;

// save to core data

}
试试这个:

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
   Lists *lists = [NSEntityDescription insertNewObjectForEntityForName:@"Lists" inManagedObjectContext:_managedObjectContext];
    if (buttonIndex != 0 && alertView.tag == 2) {
        NSString *name = [alertView textFieldAtIndex:0].text;
        UITextField *tf = [alertView textFieldAtIndex:0];
        list.name =tf.text;
}
    {
        NSError *error = nil;
        if (![_managedObjectContext save:&error]){
            Handle;
        }
}

}