2010-03-27 16 views
7

Sto utilizzando CoreData con iPhone SDK. Sto facendo un'app per appunti. Ho una tabella con gli oggetti nota visualizzati dal mio modello. Quando si preme un pulsante, voglio salvare il testo nella vista testo sull'oggetto che si sta modificando. Come faccio a fare questo? Ho provato diverse cose ma nessuna sembra funzionare.Salva oggetto in CoreData

Grazie

EDIT:

NSManagedObjectContext *context = [fetchedResultsController managedObjectContext]; 
NSEntityDescription *entity = [[fetchedResultsController fetchRequest] entity]; 
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; 
[newManagedObject setValue:detailViewController.textView.text forKey:@"noteText"]; 

NSError *error; 
if (![context save:&error]) { 
    /* 
    Replace this implementation with code to handle the error appropriately. 

    abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button. 
    */ 
    NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
    abort(); 
} 

Il codice precedente salva correttamente ma lo salva come un nuovo oggetto. Voglio che venga salvato come quello che ho selezionato nel mio TableView.

risposta

14

Si consiglia di controllare il Core Data Programming Guide. E 'difficile sapere esattamente quello che vuoi dalla domanda, ma l'idea di base è:

-(IBAction)saveNote { //hooked up in Interface Builder (or programmatically) 
    self.currentNote.text = self.textField.text; //assuming currentNote is an NSManagedObject subclass with a property called text, and textField is the UITextField 
} 

//later, at a convenient time such as application quit 
NSError *error = nil; 
[self.managedObjectContext save:&error]; //saves the context to disk 

EDIT: Se si vuole modificare un oggetto preesistente, si dovrebbe ottenere l'oggetto dal controller risultati inverosimile, per esempio NSManagedObject *currentObject = [fetchedResultsController objectAtIndexPath:[self.tableView indexPathForSelectedRow]], quindi modificare quell'oggetto. Ti consigliamo inoltre di utilizzare una sottoclasse personalizzata di NSManagedObject con dichiarazioni di proprietà, anziché utilizzare setValue:forKey, poiché è più flessibile.

+0

Grazie, in realtà ha appena funzionato. Ho dovuto modificarlo un po 'perché sto lavorando con l'iPad ma fondamentalmente lo stesso codice. Grazie – John

Problemi correlati