Pregunta

So I have a UIAlertView that has two buttons and a TextField, my problem is I would like to save the text the user enters in the text field save into a string "name" that I have in core data. All my core data programing is correct, I used it with a UITextField just not one on an alertview. I just don't know how to save what the user enters into the UIAlertView's TextField. If someone can help me out it would be greatly appreciated.

Here is what my alert view looks like: http://gyazo.com/8eba23f1fb1f5fbe49738af9185e689f

My code for the 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
    }
¿Fue útil?

Solución

Try This:

- (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;
        }
}

}

Otros consejos

You will need to use the UIAlertViewDelegate to capture to the user input from the UITextField in the alert view.

Let's tell the UIAlertView that you're going to be using the delegate, like this:

UIAlertView *alert = ...; 
//other UIAlertView settings here 
alert.delegate = self;

Next, implement the following delegate method in your code:

- (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex  
{
    if ([buttonIndex != 0 && alertView.tag == 2) {
          NSString *name = [alertView textFieldAtIndex:0].text;
    }
}

Of course, in order for the delegate method to be called, you'll also need to conform to the delegate in your header file:

@interface CustomViewController : UIViewController <UIAlertViewDelegate>  

You need to extract the string from the textfield when the delegate method is called.

- (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

}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top