Core Data에서 기존 개체를 업데이트하는 방법은 무엇입니까?
새 개체를 삽입 할 때 다음 코드를 사용합니다.
NSManagedObjectContext *context = [appDelegate managedObjectContext];
Favorits *favorits = [NSEntityDescription insertNewObjectForEntityForName:@"Favorits" inManagedObjectContext:context];
favorits.title = @"Some title";
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops");
}
핵심 데이터의 기존 개체를 어떻게 업데이트 할 수 있습니까?
업데이트는 새로운 것을 만드는 것처럼 간단합니다.
특정 개체를 업데이트하려면 NSFetchRequest
. 이 클래스는 SQL 언어의 SELECT 문과 동일합니다.
다음은 간단한 예입니다.
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Favorits" inManagedObjectContext:moc]];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
// error handling code
배열 results
에는 sqlite 파일에 포함 된 모든 관리 개체가 포함됩니다. 특정 개체 (또는 더 많은 개체)를 가져 오려면 해당 요청과 함께 술어를 사용해야합니다. 예를 들면 :
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"title == %@", @"Some Title"];
[request setPredicate:predicate];
이 경우 results
제목이와 같은 개체를 포함합니다 Some Title
. 술어를 설정하는 것은 SQL 문에 WHERE 절을 넣는 것과 같습니다.
자세한 정보는 Core Data 프로그래밍 가이드 및 NSFecthRequest
클래스 참조 를 읽어 보시기 바랍니다 .
도움이 되었기를 바랍니다.
편집 (업데이트에 사용할 수있는 스 니펫)
// maybe some check before, to be sure results is not empty
Favorits* favoritsGrabbed = [results objectAtIndex:0];
favoritsGrabbed.title = @"My Title";
// save here the context
또는 NSManagedObject
하위 클래스를 사용하지 않는 경우 .
// maybe some check before, to be sure results is not empty
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:@"My title" forKey:@"title"];
// save here the context
두 경우 모두 save
컨텍스트에서 를 수행하면 데이터가 업데이트됩니다.
컨텍스트에서 객체 를 가져 와서 원하는 속성을 변경 한 다음 예제에서와 같이 컨텍스트를 저장해야합니다.
이것이 도움이되기를 바랍니다. 그것은 나를 위해 작동합니다.
NSMutableArray *results = [[NSMutableArray alloc]init];
int flag=0;
NSPredicate *pred;
if (self.txtCourseNo.text.length > 0) {
pred = [NSPredicate predicateWithFormat:@"courseno CONTAINS[cd] %@", self.txtCourseNo.text];
flag=1;
} else {
flag=0;
NSLog(@"Enter Corect Course number");
}
if (flag == 1) {
NSLog(@"predicate: %@",pred);
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]initWithEntityName:@"Course"];
[fetchRequest setPredicate:pred];
results = [[self.context executeFetchRequest:fetchRequest error:nil] mutableCopy];
if (results.count > 0) {
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:self.txtCourseName.text forKey:@"coursename"];
[self.context save:nil];
[self showData];
} else {
NSLog(@"Enter Corect Course number");
}
}
당신이 신속한 프로그래머라면 이것이 당신을 도울 수 있습니다 :
NSManagedObject를 삭제하려는 경우
내 경우 ID는 엔티티 STUDENT의 고유 속성입니다.
/** for deleting items */
func Delete(identifier: String) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "STUDENT")
let predicate = NSPredicate(format: "ID = '\(identifier)'")
fetchRequest.predicate = predicate
do
{
let object = try context.fetch(fetchRequest)
if object.count == 1
{
let objectDelete = object.first as! NSManagedObject
context.delete(objectDelete)
}
}
catch
{
print(error)
}
}
NSManagedObject를 업데이트하려는 경우 :
/** for updating items */
func Update(identifier: String,name:String) {
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let fetchRequest:NSFetchRequest<NSFetchRequestResult> = NSFetchRequest.init(entityName: "STUDENT")
let predicate = NSPredicate(format: "ID = '\(identifier)'")
fetchRequest.predicate = predicate
do
{
let object = try context.fetch(fetchRequest)
if object.count == 1
{
let objectUpdate = object.first as! NSManagedObject
objectUpdate.setValue(name, forKey: "name")
do{
try context.save()
}
catch
{
print(error)
}
}
}
catch
{
print(error)
}
}
Objective-C에서 도움이 된 답변을 보았습니다. Swift 사용자를위한 답변을 게시하고 있습니다.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate
else
{
return
}
let updateCont = appDelegate?.persistentContainer.viewContext
let pred = NSPredicate(format: "your_Attribute_Name = %@", argumentArray : [your_Arguments])
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "your_Entity_Name")
request.predicate = pred
do {
let resul = try updateCont?.fetch(request) as? [NSManagedObject]
let m = resul?.first
m?.setValue(txtName.text, forKey: "your_Attribute_Name_Whose_Value_Should_Update")
try? updateCont?.save()
}catch let err as NSError
{
print(err)
}
참고URL : https://stackoverflow.com/questions/10571786/how-to-update-existing-object-in-core-data
'development' 카테고리의 다른 글
자바 스크립트는 대소 문자를 구분하지 않고 문자열 비교 (0) | 2020.12.03 |
---|---|
ValueError : 파이썬 형식의 길이가 0 인 필드 이름 (0) | 2020.12.03 |
iPad Mini 화면 크기 다루기 (0) | 2020.12.03 |
CSS 또는 JavaScript에서 이미지 색상 반전 (0) | 2020.12.03 |
프로젝트에있는 폴더에서 파일 읽기 (0) | 2020.12.03 |