0

总的来说,我对 Core Data 编程和 Cocoa 很陌生,所以难怪我会遇到麻烦 :)

所以这是我的 managedObjectModel 方法:

- (NSManagedObjectModel *)managedObjectModel
{
    if (managedObjectModel != nil)
    {
        return managedObjectModel;
    }
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"Model" ofType:@"momd"];
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath];

    NSAssert(modelURL != nil,@"modelURL == nil");
    managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return managedObjectModel;
}

这是崩溃的代码部分:

NSManagedObjectModel *mom = [self managedObjectModel];

managedObjectModel = mom;

if (applicationLogDirectory() == nil)
{
    NSLog(@"Could not find application logs directory\nExiting...");
    exit(1);
}

NSManagedObjectContext *moc = [self managedObjectContext];
NSProcessInfo *processInfo = [NSProcessInfo processInfo];

NSEntityDescription *newShotEntity = [[mom entitiesByName] objectForKey:@"Entity"];

Entity *shEnt = [[Entity alloc] initWithEntity:newShotEntity insertIntoManagedObjectContext:moc];


shEnt.pid = [processInfo processIdentifier]; // EXC_BAD_ACCESS (code=1, address=0x28ae) here !!!

NSError *error;

if (![moc save: &error])
{
   NSLog(@"Error while saving\n%@",
        ([error localizedDescription] != nil) ? [error localizedDescription] : @"Unknown Error");
        exit(1);
}

我真的很困惑为什么会出现这个错误,因为当我硬编码数据模型而不是使用 .xcdatamodeld 文件时,它工作得很好!

任何形式的帮助都非常感谢!

编辑1:因为我问了所有这些问题,所以我想把一切都说清楚,很抱歉之前没有提供所有这些。

    // Entity.h

    #import <CoreData/CoreData.h>

    @interface Entity : NSManagedObject

    @property (strong) NSDate *date;
    @property (assign) NSInteger pid;

    @end

   //Entity.m

   #import "Entity.h"

   @interface Entity ()
   @property (strong) NSDate *primitiveDate;
   @end

   @implementation Entity

  @dynamic date,primitiveDate,pid;


  - (void) awakeFromInsert
  {
    [super awakeFromInsert];
    self.primitiveDate = [NSDate date];
  }


  - (void)setNilValueForKey:(NSString *)key
  {
    if ([key isEqualToString:@"pid"]) {
        self.pid = 0;
    }
    else {
        [super setNilValueForKey:key];
    }

  }
  @end
4

1 回答 1

1

在核心数据中使用标量值比使用推荐的NSNumber. 这在核心数据编程指南的这一部分中有详细描述。

我强烈建议您将此属性切换为 NSNumber。你的赋值语句将是:

shEnt.pid = [NSNumber numberWithInt:[processInfo processIdentifier]];
于 2012-11-06T06:10:33.007 回答