在iOS中删除和更新Core Data中的数据

嗨,我是iOS中核心数据的新手,我已经实现了4个文本字段,即姓名,年龄,公司,地址。 现在,当用户输入数据时,我将数据保存在Core Data中。

NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSManagedObject *newContact; newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context]; [newContact setValue: _name.text forKey:@"name"]; [newContact setValue: _address.text forKey:@"address"]; [newContact setValue: _age.text forKey:@"age"]; [newContact setValue:_company.text forKey:@"company 

同样,我可以在这些文本字段中获取和显示数据。

AppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];

 NSManagedObjectContext *context = [appDelegate managedObjectContext]; NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Device" inManagedObjectContext:context]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; [request setEntity:entityDesc]; NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", _name.text]; [request setPredicate:pred]; NSManagedObject *matches = nil; NSError *error; NSArray *objects = [context executeFetchRequest:request error:&error];matches = objects[0]; _address.text = [matches valueForKey:@"address"]; _age.text = [matches valueForKey:@"age"]; _company.text = [matches valueForKey:@"company"]; 

现在,当我想删除和更新特定用户的数据时,我无法获取数据。

如何删除数据并更新..?

我已经浏览了这个链接http://www.appcoda.com/core-data-tutorial-update-delete/

预先感谢

您可以删除以下数据:

  NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"entityname" inManagedObjectContext:context]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userID like %@",userID]; [fetchRequest setEntity:entity]; [fetchRequest setPredicate:predicate]; NSError *error; NSArray *items = [context executeFetchRequest:fetchRequest error:&error]; for (NSManagedObject *managedObject in items) { [context deleteObject:managedObject]; } 

并为更新:

 NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"entityname" inManagedObjectContext:context]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userID like %@",userID]; [fetchRequest setPredicate:predicate]; [fetchRequest setFetchLimit:1]; [fetchRequest setEntity:entity]; NSError *error; NSArray *arrResult = [context executeFetchRequest:fetchRequest error:&error]; YourEntityname *entity = arrResult[0]; entity.userID = @"2" [appdelegate saveContext]; 

要首先更新NSManagedObject,您需要从获取数组中获取对象并更改此对象的值并再次保存

 *NSError *error; if (![[self managedObjectContext] save:&error]) { NSLog(@"%@",[error1 localizedDescription]); } else { NSLog(@"save Successfully") } 

删除

 [[self managedObjectContext] deleteObject:<#(nonnull NSManagedObject *)#>] 

传递要删除的NSManage对象

斯威夫特3: –

创建记录。

具有两个属性名称,编号的人员实体。

 let person = NSEntityDescription.insertNewObject(forEntityName: "Person", into: manageObjectContext) as! Person person.name = "<#name string#>" person.number = "<#number string#>" do { try manageObjectContext.save() } catch { print(error.localizedDescription) } 

获取记录

  var Per = [Person]() let fetchRequest = NSFetchRequest(entityName: "Person") do { Per = try manageObjectContext().fetch(fetchRequest) as! [Person] } catch { print(error.localizedDescription) } 

更新记录

 ler person = per[0] person.name = "<#name string#>" person.number = "<#number string#>" do { try manageObjectContext.save() } catch { print(error.localizedDescription) } 

删除记录:

 let person = per[0] self.manageObjectContext().delete(person) do { try manageObjectContext().save() } catch { print(error.localizedDescription) } 

要删除核心数据中的对象,可以使用此代码:传递要删除的实体名称…

 -(void)deleteAllObjects: (NSString *)entityName{ NSFetchRequest *request=[NSFetchRequest fetchRequestWithEntityName:entityName]; NSError *error; NSArray *items =[self.managedObjectContext executeFetchRequest:request error:&error]; for (NSManagedObject *managedObject in items) { [self.managedObjectContext deleteObject:managedObject]; } if(![self.managedObjectContext save:&error]){ NSLog(@"Error deleting: %@ - error: %@",entityName,error); } } 
  1. 首先,您已创建具有属性的实体。 参考图像
  2. 示例TripLog是一个实体,属性是date,startLat,startLong,endLat,endLatitude。
  3. 创建NSManagement文件TripLog。 h和TripLog。 米

    TripLog.h包含@property的变量声明。 TripLog.m包含变量的实现。

  4. 为TripLog创建类别文件(添加)。
  5. 创建NSObject文件以对selectData,updateData,DeleteData进行操作。

    实体文件:Code Snap TripLog.h

     @interface TripLog : NSManagedObject @property (nullable, nonatomic, retain) NSString *date; @property (nullable, nonatomic, retain) NSString *startLatitude; @property (nullable, nonatomic, retain) NSString *startLongitude; @property (nullable, nonatomic, retain) NSString *endLatitude; @property (nullable, nonatomic, retain) NSString *endLongitude; @property (nullable, nonatomic, retain) NSNumber *distance; @end 

    TripLog.m

     @implementation TripLog @dynamic date; @dynamic startLatitude; @dynamic startLongitude; @dynamic endLatitude; @dynamic endLongitude; @dynamic distance; @end 

    类别文件:代码Snap

    TripLog + Addition.h

     #import "TripLog.h" @interface TripLog (Addition) + (TripLog *)indexWithDictionary:(NSDictionary *)dict inManagedObjectContext:(NSManagedObjectContext *)context; @end 

    TripLog + Addition.m

     #import "TripLog+Addition.h" @implementation TripLog (Addition) + (TripLog *)indexWithDictionary:(NSDictionary *)dict inManagedObjectContext:(NSManagedObjectContext *)context { TripLog *indexValues = [NSEntityDescription insertNewObjectForEntityForName:@"TripLog" inManagedObjectContext:context]; indexValues.date = [dict valueForKey:@"date"]; indexValues.startLatitude = [dict valueForKey:@"startLatitude"]; indexValues.startLongitude = [dict valueForKey:@"startLongitude"]; indexValues.endLatitude = [dict valueForKey:@"endLatitude"]; indexValues.endLongitude = [dict valueForKey:@"endLongitude"]; indexValues.distance = [NSNumber numberWithDouble:[[dict valueForKey:@"distance"]doubleValue]]; return indexValues; } @end 

    NSObjectFile:DataManager

      #import "TripLog.h" @protocol DataManagerDelegate; @interface DataManager : NSObject{ } @property (nonatomic, strong) UIManagedDocument *dataDocument; @property (nonatomic, assign) id  delegate; @property (nonatomic, strong) TripLog *tripLog; @property (nonatomic, retain, readonly) NSManagedObjectModel * managedObjectModel; @property (nonatomic, retain, readonly) NSManagedObjectContext *managedObjectContext; @property (nonatomic, retain, readonly) NSPersistentStoreCoordinator *persistentStoreCoordinator; + (DataManager *)sharedInstance; -(void)saveTripLogDetails:(NSDictionary *)tripLogDict; - (void)updateTripLog:(NSDictionary *)tripLogDict; - (void)deleteTripLog:(id)object; -(NSArray *)getTripLogDetails; @end @protocol DataManagerDelegate  @optional - (void)didFinishSaving:(DataManager *)dataManager; @end 

    Datamanager.m文件

     #import "DataManager.h" #import "AppDelegate.h" #import "TripLog+Addition.h" @interface DataManager () - (void)contextDidSave:(NSNotification *)notification; @end @implementation DataManager @synthesize dataDocument; @synthesize delegate; @synthesize managedObjectContext = _managedObjectContext; @synthesize managedObjectModel = _managedObjectModel; @synthesize persistentStoreCoordinator = _persistentStoreCoordinator; #pragma mark - SharedInstance + (DataManager *)sharedInstance { static DataManager *sharedInstance = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ sharedInstance = [[DataManager alloc] init]; }); return sharedInstance; } - (id)init { self = [super init]; if (self) { // Initialise the classe // Create the Core Data document NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; url = [url URLByAppendingPathComponent:@"Gridz.sqlite"]; self.dataDocument = [[UIManagedDocument alloc] initWithFileURL:url]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Gridz.sqlite"]; if([[NSFileManager defaultManager] fileExistsAtPath:filePath]){ [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil]; } // Set our document up for automatic migrations NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil]; self.dataDocument.persistentStoreOptions = options; [self setupDocument]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:self.dataDocument.managedObjectContext]; } return self; } - (NSString *)applicationDocumentsDirectory { return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; } #pragma mark - Context Notification Methods - (void)objectsDidChange:(NSNotification *)notification { NSLog(@"NSManagedObjects did change."); [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:) name:NSManagedObjectContextDidSaveNotification object:self.dataDocument.managedObjectContext]; } - (void)contextDidSave:(NSNotification *)notification { NSlog(@"NSManagedContext did save."); [[NSNotificationCenter defaultCenter] removeObserver:self name:NSManagedObjectContextDidSaveNotification object:self.dataDocument.managedObjectContext]; if ([delegate respondsToSelector:@selector(didFinishSaving:)]) { [delegate didFinishSaving:self]; } } #pragma mark - Setup Document - (void)setupDocument { if (![[NSFileManager defaultManager] fileExistsAtPath:[self.dataDocument.fileURL path]]) { LOG(@"does not exist on disk, so create it"); // does not exist on disk, so create it [self.dataDocument saveToURL:self.dataDocument.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) { }]; } else if (self.dataDocument.documentState == UIDocumentStateClosed) { LOG(@"exists on disk, but we need to open it"); // exists on disk, but we need to open it [self.dataDocument openWithCompletionHandler:^(BOOL success) { }]; } else if (self.dataDocument.documentState == UIDocumentStateNormal) { LOG(@"UIDocumentStateNormal"); } } -(void)saveTripLogDetails:(NSDictionary *)tripLogDict { self.tripLog =[TripLog indexWithDictionary:tripLogDict inManagedObjectContext:self.dataDocument.managedObjectContext]; } - (void)deleteTripLog:(id)object { if (object) { [self.dataDocument. managedObjectContext deleteObject: indexObject]; } } -(NSArray *)getTripLogDetails{ NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"TripLog" inManagedObjectContext:self.dataDocument.managedObjectContext]; NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"distance" ascending:YES]; fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setEntity:entity]; NSError *error = nil; NSArray *fetchedObjects = [self.dataDocument.managedObjectContext executeFetchRequest:fetchRequest error:&error]; return fetchedObjects; } -(void)updateTripLog :(NSMutableDictionary *)dict { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"TripLog" inManagedObjectContext:self.dataDocument.managedObjectContext]; NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES]; fetchRequest.predicate = [NSPredicate predicateWithFormat:@"((date== %@))",[dict valueForKey:@"date"]]; fetchRequest.sortDescriptors = [NSArray arrayWithObject:sortDescriptor]; [fetchRequest setEntity:entity]; NSError *error = nil; NSArray *fetchedObjects = [self.dataDocument.managedObjectContext executeFetchRequest:fetchRequest error:&error]; if([fetchedObjects count]>0){ TripLog *indexValues = [fetchedObjects objectAtIndex:0]; indexValues.date = [dict valueForKey:@"date"]; indexValues.startLatitude = [dict valueForKey:@"startLatitude"]; indexValues.startLongitude = [dict valueForKey:@"startLongitude"]; indexValues.endLatitude = [dict valueForKey:@"endLatitude"]; indexValues.endLongitude = [dict valueForKey:@"endLongitude"]; indexValues.distance = [NSNumber numberWithDouble:[[dict valueForKey:@"distance"]doubleValue]]; }else [self saveTripLogDetails:dict]; //insert Dictionary } 

    @结束

    使用Viewcontroller中的DataManger文件

    1. 将“TripLog.h”文本导入顶部

    2. 在viewDidLoad中

        NSArray *tripDetails = [[DataManager sharedInstance] getTripDetails]; TripLog *tribLog = [tripDetails objectAtIndex:0]; NSLog(@"TripDate:%@",tribLog.date); [[DataManager sharedInstance]deleteTripDetails:tribLog]; //delete the tripDetails 
  func Update(name: String , address : String , mobile : String , email : String , imgs : NSString) { guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } let managedContext = appDelegate.persistentContainer.viewContext let entity = NSEntityDescription.entity(forEntityName: "Person", in: managedContext)! //let fetchRequest = NSFetchRequest(entityName: "entity") let fetchRequest = NSFetchRequest(entityName: "Person") do { let array_users = try managedContext.fetch(fetchRequest) let people = array_users[0] as NSManagedObject //let person = NSManagedObject(entity: entity, insertInto: managedContext) people.setValue(name, forKeyPath: "name") people.setValue(address, forKeyPath: "address") people.setValue(imgs, forKeyPath: "img") people.setValue(email, forKeyPath: "mailid") people.setValue(mobile, forKeyPath: "mobile") //save the context do { try managedContext.save() print("saved!") } catch let error as NSError { print("Could not save \(error), \(error.userInfo)") } catch { } } catch { print("Error with request: \(error)") } }