核心数据保存和加载到多个实体

发布于 2024-10-21 05:34:15 字数 3841 浏览 10 评论 0原文

核心数据菜鸟在这里。

我有一个项目,它将数据保存到单个实体没有问题。但是,由于该实体具有太多属性(超过 100 个),它会收到一条警告,提示我需要对其进行标准化。好的,所以我创建了第二个实体来存储更多具有一对一关系的数据。

问题是,当我尝试保存数据时,数据会保存并重新加载到第一个实体,但不会从第二个实体保存或重新加载。我一定错过了一些简单的东西。

这是一些代码:

//ViewDidLoad
    - (void)viewDidLoad
{
    if (managedObjectContext == nil) {
        managedObjectContext = [(CoreDataStuffAppDelegate *) [[UIApplication sharedApplication] delegate] managedObjectContext];
        NSLog(@"After managedObjectContext: %@", managedObjectContext);
    }

   // [self addRecord];
    [super viewDidLoad];

    if ([self fetchData]) {
        NSLog(@"after self fetchData patientArray count is %i", [parentArray count]);
        if ([parentArray count] == 1) {
            Parent *parentInfo = (Parent *)[parentArray objectAtIndex:0];
            parentItem1.text = parentInfo.Mother;
            NSLog(@"fetching on load %i", [parentArray count]);

            //Try 1:  just going after the relationship route (FAIL:  cuz data wont store.  stays null)
         //   childItem1.text = parentInfo.ParentToChild.Kid;

              // Try 2:  going the route of directly talking to the second entity
            childItem1.text = child.Kid;
        }
    }

// Save Record
    - (void)saveRecord{
    if (managedObjectContext == nil) {
        NSLog(@"there is no context, arrg");

    }
    NSLog(@"array count is %i", [parentArray count]);
    if ([parentArray count] == 1) {
        NSManagedObjectContext *context = managedObjectContext;//[parent managedObjectContext];
        NSLog(@"context 1 is: %@", context);

        Parent *parentInfo = (Parent *)[parentArray objectAtIndex:0];
        parentInfo.Mother = parentItem1.text;
        NSLog(@"data says: %@", parentInfo.Mother);
        NSLog(@"text syas: %@", parentItem1.text);

        // Try 1, save it through the child relationship thing.  (failed)
    //    parentInfo.ParentToChild.Kid = childItem1.text;
    //    NSLog(@"childSave says: D: %@ T: %@", parentInfo.ParentToChild.Kid , childItem1.text);

       // Try 2.  from Resipeas app
        if (!child) {
            self.child = [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:context];
            [parent addChildObject:child];
            NSLog(@"I hit the child");

        }
        child.Kid = childItem1.text;
        NSLog(@"1: childSave says: D: %@ T: %@", parentInfo.ParentToChild.Kid , childItem1.text);
        NSLog(@"2: childSave says: D: %@ T: %@", child.Kid , childItem1.text);



        NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"context 2 is: %@", context);
            NSLog(@"major fail %@", [error localizedDescription]);
         //   abort();
        }
    }
    NSLog(@"saving stuff");

}

// FetchData
- (BOOL)fetchData {
    NSLog(@"doing the fetch");
    BOOL returnResult = FALSE;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    if (managedObjectContext == nil) 
    { 
        NSLog(@"ok making a new managed object context");
        managedObjectContext = [(CoreDataStuffAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    }

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setFetchBatchSize:1];
    NSError *error;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        NSLog(@"Fetching Error");
    } else {
        [self setParentArray:mutableFetchResults];
        returnResult = TRUE;
        NSLog(@"Fetching went well");
    }

    [mutableFetchResults release];
    [fetchRequest release];

    return (returnResult);
}

Core Data Noob here.

I have a project, it saves data to a single entity no problemo. However, because the entity has way too many properties (over 100) it gets a warning that I need to normalize it. OK, so i create a second entity to store more data with To-One relationships both ways.

Problem is that when i try to save data, data saves and reloads to the first entity, but will not save or reload from the second. I must be missing something simple.

Here is some code:

//ViewDidLoad
    - (void)viewDidLoad
{
    if (managedObjectContext == nil) {
        managedObjectContext = [(CoreDataStuffAppDelegate *) [[UIApplication sharedApplication] delegate] managedObjectContext];
        NSLog(@"After managedObjectContext: %@", managedObjectContext);
    }

   // [self addRecord];
    [super viewDidLoad];

    if ([self fetchData]) {
        NSLog(@"after self fetchData patientArray count is %i", [parentArray count]);
        if ([parentArray count] == 1) {
            Parent *parentInfo = (Parent *)[parentArray objectAtIndex:0];
            parentItem1.text = parentInfo.Mother;
            NSLog(@"fetching on load %i", [parentArray count]);

            //Try 1:  just going after the relationship route (FAIL:  cuz data wont store.  stays null)
         //   childItem1.text = parentInfo.ParentToChild.Kid;

              // Try 2:  going the route of directly talking to the second entity
            childItem1.text = child.Kid;
        }
    }

// Save Record
    - (void)saveRecord{
    if (managedObjectContext == nil) {
        NSLog(@"there is no context, arrg");

    }
    NSLog(@"array count is %i", [parentArray count]);
    if ([parentArray count] == 1) {
        NSManagedObjectContext *context = managedObjectContext;//[parent managedObjectContext];
        NSLog(@"context 1 is: %@", context);

        Parent *parentInfo = (Parent *)[parentArray objectAtIndex:0];
        parentInfo.Mother = parentItem1.text;
        NSLog(@"data says: %@", parentInfo.Mother);
        NSLog(@"text syas: %@", parentItem1.text);

        // Try 1, save it through the child relationship thing.  (failed)
    //    parentInfo.ParentToChild.Kid = childItem1.text;
    //    NSLog(@"childSave says: D: %@ T: %@", parentInfo.ParentToChild.Kid , childItem1.text);

       // Try 2.  from Resipeas app
        if (!child) {
            self.child = [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:context];
            [parent addChildObject:child];
            NSLog(@"I hit the child");

        }
        child.Kid = childItem1.text;
        NSLog(@"1: childSave says: D: %@ T: %@", parentInfo.ParentToChild.Kid , childItem1.text);
        NSLog(@"2: childSave says: D: %@ T: %@", child.Kid , childItem1.text);



        NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"context 2 is: %@", context);
            NSLog(@"major fail %@", [error localizedDescription]);
         //   abort();
        }
    }
    NSLog(@"saving stuff");

}

// FetchData
- (BOOL)fetchData {
    NSLog(@"doing the fetch");
    BOOL returnResult = FALSE;
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    if (managedObjectContext == nil) 
    { 
        NSLog(@"ok making a new managed object context");
        managedObjectContext = [(CoreDataStuffAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
    }

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Parent" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];
    [fetchRequest setFetchBatchSize:1];
    NSError *error;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        NSLog(@"Fetching Error");
    } else {
        [self setParentArray:mutableFetchResults];
        returnResult = TRUE;
        NSLog(@"Fetching went well");
    }

    [mutableFetchResults release];
    [fetchRequest release];

    return (returnResult);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

南风起 2024-10-28 05:34:15

好吧,首先,我认为你在这里有一个概念问题,因为我从未见过需要一个具有 100 个属性的实体。大多数实体都有大约 6 个属性,我认为我见过的属性最多约为 20 个。

核心数据首先是一个对象图管理系统,其中包含持久性作为一个选项。它旨在实现模型-视图-控制器(MVC)设计的模型层。因此,核心数据主要是对数据进行建模而不是存储数据。

实体旨在表示某些现实世界的对象、条件或事件。现实世界中具有 100 个属性的事物并不多。例如,您想要制作一个人的详细模型。您需要诸如名字、姓氏、地址(包含每个地址组成部分的属性)、驾驶执照#和颁发日期、工作地点及其地址、社会安全号码等信息。如果您试图将所有这些信息塞进一个Person 实体,您最终可能会获得许多属性。然而,如果您仔细观察正在建模的数据以及数据内的关系,您会注意到在现实世界中,地址、驾驶执照、工作地点等实际上并不是真实人物的属性,而是其他真实对象的属性与真实人物相关。因此,最好的方法是将这些对象的属性分解为单独的实体,并创建与 Person 实体的关系。这也使得模型更加真实。毕竟,可以有多个人住在同一地址或在同一地点工作。

因此,您可能需要从头开始并重新考虑您的数据模型设计。

确保您了解实体和托管对象之间的区别。实体是抽象的,仅用于定义托管对象的键、值类型和关系。实体对于托管对象就像类对于实例一样。

您还有另外两个问题:

(1) 如果您为实体定义了自定义 NSManagedObject 子类,则只能使用点语法访问器形式,例如 parentInfo.ParentToChild.Kid。否则,您将使用通用 NSManagedObject 实例,并且必须使用键值方法,例如 [parent setvalue:forKey]

(2) 一次获取仅返回一个实体的对象。因此,如果您有一个父实体和一个子实体。每次获取都会返回父级或子级的实例,但不会同时返回两者(除非它们都继承自获取的实体。)

Okay, firstly, I think you have a conceptual problem here because I have never seen the need for an entity with 100 attributes. Most entities have a around a half-dozen attributes and I think the most I've ever seen was around 20.

Core Data is first and foremost an object graph management system with persistence tossed in as an option. It is intended to implement the model layer of a Model-View-Controller(MVC) design. As such, Core Data is primarily about modeling data not storing it.

Entities are intended to represent some real-world object, condition or event. There aren't a lot of real-world things that have a 100 attributes. E.g. You want to make a detailed model of a person. You want things like first name, last name, address(with attributes for each address component), driver's license# and date of issue, place of employment with address, social security number etc. If you tried to cram all that into one Person entity you could end up with a dozens of attributes. However, if you look closely at the data you are modeling and the relationships within the data, you would note that in the real world, addresses, driver's license, places of employment etc are not actually attributes of real people but rather other real-objects related to real people. Therefore, the best approach would be to break out the attributes for those objects into separate entities and create relationships to the Person entity. This makes model more realistic as well. After all, more than one person can live at the same address or work at the same place.

So, you probably need to start over from scratch and rethink your data model design.

Make sure you understand the difference between entities and managedObjects. Entities are abstract and serve merely to define keys, value types and relationships for managedObjects. Entities are to managedObjects as classes are to instances.

You have two other problems:

(1) You can only use the dot syntax accessor forms e.g parentInfo.ParentToChild.Kid if you have defined custom NSManagedObject subclasses for your entities. Otherwise, you are using generic NSManagedObject instances and must use the key-value methods e.g. [parent setvalue:forKey].

(2) A fetch returns only objects of one entity. So if you have a Parent entity and a Child entity. Each fetch returns instances of either Parent or Child but never both (unless they both inherit from the fetch's entity.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文