如何打印出Core Data对象?

时间:2014-09-05 14:11:45

标签: ios debugging core-data printing entities

我想在NSLog语句中的代码中打印存储在Core Data对象中的数据。

背景信息:我正在从PList中读取数据以进行预填充,然后将其转移到Core Data。发布的应用程序只能从Core Data中读取。

这是我的PList的样子:

Recipes.plist

这是我的对象图:

object graph

这是我的代码:

-(void)initXML
{
    [self deleteAllEntities:@"Recipes"];

    [self copyXMLtoEntities];

    [self printEntities];
}

_

// deletes data from all entities to ready them for pre-population
-(void)deleteAllEntities:(NSString *)entityDescription
{
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityDescription inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    NSError *error;
    NSArray *items = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    for (NSManagedObject *managedObject in items)
    {
        [self.managedObjectContext deleteObject:managedObject];
        DLog(@"%@ ..object deleted", entityDescription);
    }

    if (![self.managedObjectContext save:&error])
    {
        DLog(@"Error deleting %@ - error:%@", entityDescription, error);
    }
}

_

// This copies data from the PList to Core Data Entities, aka pre-population
-(void)copyXMLtoEntities
{        
    NSDictionary *allRecipesDictionary = [self getRecipes];
    DLog(@"allRecipes: [%@]", allRecipesDictionary);

    Recipes *recpies = [NSEntityDescription insertNewObjectForEntityForName:@"Recipes" inManagedObjectContext:self.managedObjectContext];

    for (NSString *recipeKey in allRecipesDictionary)
    {
        NSDictionary *recipeDict = [allRecipesDictionary objectForKey:recipeKey];

        Recipe *recipe = [NSEntityDescription insertNewObjectForEntityForName:@"Recipe" inManagedObjectContext:self.managedObjectContext];
        recipe.id = recipeKey;
        recipe.name = [recipeDict objectForKey:@"name"];

        NSMutableArray *contentItemsArray = [[NSMutableArray alloc] init];            

        NSArray *contentArrayToIterate = [recipeDict objectForKey:@"content"];            

        // loop through content array and add each item
        for (int i=0 ; i < [contentArrayToIterate count] ; i++)
        {
            // create text or image content items
            // add them to the array
            // create entities and add them to contentItemsArray

            NSDictionary *contentItemDict = contentArrayToIterate[i];

            NSDictionary *textItemDict = [contentItemDict objectForKey:@"textItem"];
            NSDictionary *imageItemDict = [contentItemDict objectForKey:@"imageItem"];
            NSString *sequenceStr = [contentItemDict objectForKey:@"sequence"];

            if (textItemDict != nil)
            {
                NSString *text = [textItemDict objectForKey:@"text"];
                TextItem *textItem = [NSEntityDescription insertNewObjectForEntityForName:@"TextItem" inManagedObjectContext:self.managedObjectContext];

                textItem.text = text;
                textItem.sequence = sequenceStr;

                // add entity to the array
                [contentItemsArray addObject:textItem];
            }

            if (imageItemDict != nil)
            {
                NSString *filename = [imageItemDict objectForKey:@"filename"];

                ImageItem *imageItem = [NSEntityDescription insertNewObjectForEntityForName:@"ImageItem" inManagedObjectContext:self.managedObjectContext];

                imageItem.filename = filename;
                imageItem.sequence = sequenceStr;

                // add entity to the array
                [contentItemsArray addObject:imageItem];
            }
        } // loop through content

        recipe.contentItems = [NSSet setWithArray:contentItemsArray];
        [recpies addRecipeObject:recipe];
    } // loop through recipes

    [self saveContext];
}

_

// This returns the Dictionary of Recipes
-(NSDictionary *)getRecipes
{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Recipes" ofType:@"plist"];
    NSDictionary *plist = [[NSDictionary alloc] initWithContentsOfFile:path];

    // recipes
    NSDictionary *recipes = [plist objectForKey:@"Recipes"];

    return recipes;
}

_

打印这样的字典:

DLog(@"allRecipes: [%@]", allRecipesDictionary);

给我很好的分类输出:

allRecipes: [{
    "BLUEBERRY_PIE_001" =     {
        content =         (
                           {
                               textItem =                 {
                                   sequence = 1;
                                   text = "Mix sugar, cornstarch, salt, and cinnamon, and sprinkle over blueberries.";
                               };
                           },
                           {
                               imageItem =                 {
                                   filename = "mixIngredients.jpg";
                                   sequence = 2;
                               };
                           },
                                ...

打印核心数据实体,如下所示:

DLog(@"self.recipes: [%@]", self.recipes);

或者这个:

DLog(@"| self.recipes description: [%@]", [self.recipes description]);

给我这个:

self.recipes: [(
"<Recipes: 0x9951840> (entity: Recipes; id: 0x9962730 <x-coredata://4E308A08-FB8A-44C5-887A-88C335378A14/Recipes/p2> ; data: {\n    recipe =     (\n    );\n})"

)]

如何让它看起来像字典打印输出?我能想到的直接方法是为每个迭代自己的集合的实体添加一个“print”方法。我的完整应用程序中有32个实体。每次我从对象图中生成新实体时,我都希望避免编写此代码。

更有效的方法是扫描每个实体的属性并迭代它们。此链接显示如何为属性执行此操作,但不显示关系: http://iphonedevelopment.blogspot.com/2010/08/core-data-odds-and-ends.html

你如何为关系做这项工作?

1 个答案:

答案 0 :(得分:1)

最简单的方法是

for (Recipe *r in recipesObject.recipe) { NSLog(@"%@", r); }

你会得到一些额外的不那么漂亮的核心数据输出,但如果它是用于信息或调试,它应该没问题。此外,关系可能未完全记录。

更好的是,创建一个像prettyDescription这样的方法,在其中根据自己的喜好格式化输出。您可以将它放入NSManagedObject子类或(更好)它的扩展。

-(NSString*)prettyDescription {
    NSMutableString *result = [NSMutableString new];
    [result appendString:self.name];
    [result appendString:@"\n"];
    for (ContentItem *item in self.contentItems) {
        // append details from item to the result
    }
    return [NSString stringWithString:result]; // return immutable string
}

现在您可以使用

记录所有食谱
for (Recipe *r in recipesObject.recipe) { NSLog(@"%@", r.prettyDescription); }

注意:我认为您应该重新命名您的实体和属性,以便明确说明如下:

Recipes          --> RecipesCollection
Recipes.recipe   --> RecipesCollection.recipes
Recipe.recipes   --> Recipe.collection