在核心数据中更新对象值也将创建一个新对象 [英] Updating object value in core data is also creating a new object

查看:73
本文介绍了在核心数据中更新对象值也将创建一个新对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经检查了以下问答,尽管解决方案几乎相同,但仍然存在我的问题:
保存更新的Core Data实例

I have check the following Q&A and while the solutions are much the same the issue remains for me remains: Saving an updated Core Data instance

更新/编辑coreData托管对象

如何更新核心数据中的现有对象?

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

I have a log in/log out feature in my app.

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

The Core Data entity "NewLog" has the following attributes

String loginTime
String logoutTime
String loginStatus
String name

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

When I login it creates a new object in the core data. When I log out I have the object update.The issue is when I logout it updates the existing object but creates a new object also.

这是我的超类中的保存代码,因此我不必不断重写它,而不会在我的类中冒险:

Here is my "save" code from my super class so that I don't have to continuously rewrite it and risk errors in my classes:

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

In my loginViewController implementation file to update the "loginStatus" and "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];

    }

}

当我保存时

是否有一种解决方案可以阻止新对象的创建?

Is there a solution to stop the new object being created?

谢谢

编辑

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

I know that it is creating a new object the following ways: 1. The SQL file displays the new object with the content stated above - logoutTime and loginStatus 2. The tableview displays the new object and in the detail view for it displays the two items.

检查它来自的区域是我的任务:

Checking the area it's coming from is my 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;
    }
}

我知道为什么它会创建一个新对象,但是该怎么做我可以防止这种情况的发生,同时又仍然可以保存?

I know why it's creating a new object but how do I prevent this from happening while remaining able to save?

推荐答案

问题代码中没有任何操作创建新的托管对象,因此,问题出在代码的其他地方,或者您误认为正在创建一个额外的对象-您不会说得出这个结论的方式。

Nothing in the code in your question is creating a new managed object, so either the problem is elsewhere in your code or you're mistaken that an extra object is being created - you don't say how you have come to this conclusion.

要确定问题所在,请在 NewLog awakeFromInsert >对象并添加一个断点。每次添加这些对象之一时都会被点击,然后您可以检查堆栈跟踪以找出从何处添加对象。

To identify the problem, implement awakeFromInsert on your NewLog object and add a breakpoint. This will be hit every time one of these objects is added, you can then examine the stack trace to find out where the object is being added from.

更新

好的,完成后,您会看到每次执行Segue时都要创建一个新实体。不要那样做您需要执行访存来找到现有的登录对象,并且仅当没有一个登录对象或现有的登录对象不合适时,才创建一个新的登录对象。

OK, having done that, you see that you're making a new entity every time the segue is performed. Don't do that. You need to perform a fetch to find the existing login object, and only if there isn't one, or the existing one isn't suitable, create a new one.

如果进行访存且数组中没有任何内容,则 objectAtIndex:0 将崩溃。使用 firstObject 代替,并检查结果是否为零。

If you do a fetch and there's nothing in the array, objectAtIndex:0 will crash. Use firstObject instead and check if the result of that is nil.

这篇关于在核心数据中更新对象值也将创建一个新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆