ios - 更新核心数据中的对象值也是创建一个新对象

标签 ios objective-c iphone core-data

我检查了以下问答,虽然解决方案大致相同,但问题仍然存在: Saving an updated Core Data instance

Update/Edit coreData managed object

How to update existing object in Core Data?

我的应用程序中有登录/注销功能。

核心数据实体“NewLog”具有以下属性

String loginTime
String logoutTime
String loginStatus
String name

当我登录时,它会在核心数据中创建一个新对象。当我注销时,我更新了对象。问题是当我注销时,它会更新现有对象,但也会创建一个新对象。

这是我的父类(super class)中的“保存”代码,这样我就不必不断地重写它并冒着在我的类中出错的风险:

- (void) saveAndDismiss{

    NSError * error = nil;
    if ([self.managedObjectContext hasChanges]){
        if (![self.managedObjectContext save: &error]){
            NSLog(@"Save Failed: %@", [error localizedDescription]);
        }
        else {
            NSLog(@"Save Successful");
        }
    }

    [self dismissViewControllerAnimated:YES completion:nil];

}

在我的 loginViewController 实现文件中更新“loginStatus”和“logoutTime”:

- (IBAction)logOutButton:(id)sender {

    //access the managed object context and create a shortcut name
    NSManagedObjectContext *context = [self managedObjectContext];

    //refer to the entity in the core data
    NSEntityDescription *entity = [NSEntityDescription entityForName: @"NewLog" inManagedObjectContext:context];

    //create a request
    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    [request setEntity: entity];

    // Results should be in descending order of loginTime.
    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"loginTime" ascending:NO];
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    //create an array of results
    NSArray *results = [context executeFetchRequest:request error:NULL];
    NewLog *latestEntity = [results objectAtIndex:0];

    //refer to the specific value that I wish to change
    NSString * statusOfLogin = latestEntity.loginStatus;

    //if the loginStatus in my app is currently YES
    if ([statusOfLogin isEqual:@"YES"]){

        //create a date formatter
        NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];

        //format as such
        [dateformatter setDateFormat:@"dd MMM yyyy , HH:mm:ss"];

        //convert to a string
        NSString *dateInStringFormated=[dateformatter stringFromDate:[NSDate date]];

        //hide logout button and display login button
        _logOutButton.alpha = 0.0;
        _loginButtonStatus.alpha = 1.0;

        //status declared as String in .h file
        status = @"NO";

        //update the object found in "latestEntity"
        latestEntity.logoutTime = dateInStringFormated;
        //set the login status to be NO
        latestEntity.loginStatus = status;

        //BOOL declared in the .h file
        logStatus = false;


        self.loginLabel.text = @"Logged Out";
        self.dateLabel.text = dateInStringFormated;

        [super saveAndDismiss];

    }

}

当我保存更新的数据时,它会创建一个仅包含注销时间和登录状态的新对象。

是否有停止创建新对象的解决方案?

谢谢

编辑

我知道它正在通过以下方式创建一个新对象: 1. SQL 文件显示具有上述内容的新对象 - logoutTime 和 loginStatus 2. tableview 显示新对象,在它的详细 View 中显示两个项目。

检查它来自的区域是我的 segue:

//prepare for segue
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{

    //first check whether the segue is equal to our transition name
    if([[segue identifier]isEqualToString:@"loginSegue"])
    {
        //tell the segue where to go
        UINavigationController *navigationController = segue.destinationViewController;

        //create reference to view controller
        LoginViewController *loginVC= (LoginViewController*) navigationController.topViewController;

        //create the new object
        NewLog *addLogDetails = [NSEntityDescription insertNewObjectForEntityForName:@"NewLog" inManagedObjectContext: [self managedObjectContext]];

        loginVC.logEntry = addLogDetails;
    }
}

我知道它为什么要创建一个新对象,但我如何在保持保存能力的同时防止这种情况发生?

最佳答案

您问题中的代码中没有任何内容正在创建一个新的托管对象,因此问题出在您的代码中的其他地方,或者您误认为正在创建一个额外的对象 - 您没有说明您是如何做到这一点的结论。

要确定问题,请在 NewLog 对象上实现 awakeFromInsert 并添加断点。每次添加这些对象之一时都会触发此操作,然后您可以检查堆栈跟踪以找出从何处添加对象。

更新

好的,完成后,您会看到每次执行 segue 时都会创建一个新实体。不要那样做。您需要执行一次获取以找到现有的登录对象,只有在没有或现有的不合适时,才创建一个新的。

如果您执行一次获取操作,但数组中没有任何内容,objectAtIndex:0 将会崩溃。请改用 firstObject 并检查其结果是否为 nil。

关于ios - 更新核心数据中的对象值也是创建一个新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26135604/

相关文章:

ios - 从 ios 中的另一个 View 中关闭呈现的 View Controller

iphone - 是否有适用于 iPhone 和/或 Android 手机的好的 OCR API?

ios - AVAudioPlayer 得到错误的文件持续时间 iOS 10

ios - 从 Swift 中的蓝牙读取中提取并转换 NSData 值

ios - AFNetworking 2.2.1 从 Amazon S3 服务器加载图像

ios - UIButton 无法在 iPhone 屏幕底部正确注册触摸

iphone - 从服务器下载高分辨率图像以进行视网膜显示的策略

ios - 相当于IOS中的静态字段

ios - UIProgressView 仅更新值而不是 UI

objective-c - 如何使用performSelector :withObject:afterDelay: on a method with multiple arguments