NSManagedObjectContext只能运行几次,然后停止工作

时间:2014-02-18 13:52:45

标签: ios objective-c core-data

在我试着问两次并解释自己后,我做了一个挖掘,我想我现在可以更好地解释我的问题了:

1)我正在使用核心数据保存到NSManagedObjectsCoreDataTrap& CoreDataAllTraps。 第一次,我正在解析一个大的xml,然后转换为数组,然后将细节添加到CoreDataAllTraps,这个操作很顺利,因为我做了一个日志。

2)然后,为了测试,我正在获取所有记录并记录它们的总数。

这些功能可以为我提供正确的记录数。 3)然后只是初始化一些变量。

4)然后初始化我的四叉树。

这让我回到了我的断言错误。

  

错误:fetchedObjects没有记录。

5)然后,使用核心数据的所有其他函数当然会给我错误,因为没有数据。

相关(编号)代码:

1:
---
- (void)addOrUpdateTrap:(Traps*)trapObject
{
    NSManagedObjectContext *context = generateManagedObjectContext();

    int trapID = trapObject.getTrapID;
    CoreDataAllTraps *trapEntity = nil;
    NSError *error = nil;

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:kCORE_DATA_ALL_TRAPS_ENTITY];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"trapID == %d", trapID];
    [fetchRequest setPredicate:predicate];

    NSArray *results = [context executeFetchRequest:fetchRequest error:&error];
    if (results == nil)
    {
        // Handle error
    }
    else if (results.count == 0)
    {
        // Nothing to update, add new trap
        // Create a new record (row)
        trapEntity = [NSEntityDescription insertNewObjectForEntityForName:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
    }
    else
    {
        trapEntity = results[0]; // There should be only one object for the ID.
    }


    if (trapEntity != nil)
    {
        // Set properties for new or existing object ...

        // Int
        [trapEntity setTrapID:[NSNumber numberWithInt:trapObject.getTrapID]];
        [trapEntity setType:[NSNumber numberWithInt:trapObject.getTrapType]];
        [trapEntity setDist:[NSNumber numberWithInt:trapObject.getTrapDistanceToCar]];
        [trapEntity setDist_to_close_point:[NSNumber numberWithInt:trapObject.getTrapDistanceToClosePoint]];
        [trapEntity setActive:[NSNumber numberWithInt:trapObject.isActive]];
        [trapEntity setAlert:[NSNumber numberWithInt:trapObject.isAlert]];
        [trapEntity setAlarmDistance:[NSNumber numberWithInt:trapObject.alarmDistance]];
        [trapEntity setRoadNumber:[NSNumber numberWithInt:trapObject.roadNumber]];
        [trapEntity setPolys:[NSNumber numberWithInt:trapObject.polygons]];
        [trapEntity setEnter_to_area:[NSNumber numberWithInt:trapObject.getTrapEnterToArea]];

        // Double
        [trapEntity setLat:[NSNumber numberWithDouble:trapObject.getTrapLat]];
        [trapEntity setLon:[NSNumber numberWithDouble:trapObject.getTrapLon]];
        [trapEntity setClose_point_lat:[NSNumber numberWithDouble:trapObject.getTrapClosePointLat]];
        [trapEntity setClose_point_lon:[NSNumber numberWithDouble:trapObject.getTrapClosePointLon]];

        // NSString
        [trapEntity setLastTrapAlarm:[NSString stringWithFormat:@"%li", trapObject.getTrapLastAlarm]];
        [trapEntity setPoly0:trapObject.getTrapPolygonA];
        [trapEntity setPoly1: trapObject.getTrapPolygonB];
        [trapEntity setPoly2: trapObject.getTrapPolygonC];
        [trapEntity setPolygonAzimut1: trapObject.getTrapPolygonAzimuthA];
        [trapEntity setPolygonAzimut2: trapObject.getTrapPolygonAzimuthB];
        [trapEntity setPolygonAzimut3: trapObject.getTrapPolygonAzimuthC];
        [trapEntity setDesc: trapObject.getTrapDesc];
        // etc. for all properties ...


        error = nil;
        if ([context save:&error] == NO) {
            NSLog(@"%s error saving: %@\n%@", __PRETTY_FUNCTION__, error.localizedDescription, error.userInfo);
        }
        else {
            [context reset];
        }
    }
}

2:
---
- (void)saveArray:(NSArray*)array
{
    kNETROADS_CONTEXT.arrayOfAllTraps = self.arrayOfAllTraps = array.mutableCopy;
    NSLog(@"Total number of traps: %d", self.arrayOfAllTraps.count);

    NSManagedObjectContext *context = generateManagedObjectContext();

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSLog(@"TrapService - fetchedObjects.count: %d", fetchedObjects.count);

    if (fetchedObjects == nil || fetchedObjects.count == 0) {
        NSLog(@"saveArray - localizedDescription: %@, userInfo: %@", error.localizedDescription, error.userInfo);
    }

    [self readArray];
}

- (void)readArray
{
    NSManagedObjectContext *context = generateManagedObjectContext();

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
    [fetchRequest setEntity:entity];
    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    NSLog(@"readArray - fetchedObjects.count: %d", fetchedObjects.count);

    if (fetchedObjects == nil || fetchedObjects.count == 0) {
        NSLog(@"readArray - localizedDescription: %@, userInfo: %@", error.localizedDescription, error.userInfo);
    }
}

3:
---
- (void)initVariables
{
    db = [[DataBase alloc] init];

    //dbat = [[DataBaseAllTraps alloc] init];
    dbat = [DataBaseAllTraps getInstance];

    kRECEIVER_CONTEXT.db = [[DataBase alloc] init];

    [db deleteTrapsTable];
    [dbat deleteTrapsTable];

    self.dictAddUserLocations = [[NSMutableDictionary alloc] init];
    self.arrayOfAllTraps = [Netroads sharedInstance].arrayOfAllTraps;
    self.arrayOfLocations = [[NSMutableArray alloc] init];
    self.firstOnLocationChanged = YES;
    self.mLocation = [CLLocation new];
    self.mLastLocation = [CLLocation new];
    self.globalLocation = [CLLocation new];
    self.lastGlobalLocation = [CLLocation new];
    self.myLocations = [[NSMutableArray alloc] init];
    self.accuracy = @"N/A";
    self.closeTrap = [[Traps alloc] init];

    self.notification = [NSNotificationCenter defaultCenter];
    // [self.notification addObserver:self selector:@selector(onReceive:) name:kSend_To_Receiver_Notification object:nil];
}

4:
---

- (void)initializeQuadTree
{
    self.qTree = [[QuadTree alloc] init];
    BOOL success = YES;

    NSManagedObjectContext *context = generateManagedObjectContext();

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    NSError *error = nil;
    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil || fetchedObjects.count == 0)
    {
        NSLog(@"initializeQuadTree - localizedDescription: %@, userInfo: %@", error.localizedDescription, error.userInfo);
        success = NO;
    }

    NSLog(@"initializeQuadTree - fetchedObjects.count: %d", fetchedObjects.count);

    NSAssert(fetchedObjects != nil, @"Error: fetchedObjects = nil");
    NSAssert(fetchedObjects.count > 0, @"Error: fetchedObjects have no records.");

    if (success)
    {
        for (CoreDataAllTraps *trap in fetchedObjects)
        {
            double latitude = trap.lat.doubleValue;
            double longitude = trap.lon.doubleValue;

            double closePointLat = trap.close_point_lat.doubleValue;
            double closePointLon = trap.close_point_lon.doubleValue;

            DummyAnnotation *trapAnnotation = [[DummyAnnotation alloc] init];

            if (closePointLat != 0.0 || closePointLon != 0.0) trapAnnotation.coordinate = CLLocationCoordinate2DMake(closePointLat, closePointLon);
            else trapAnnotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);

            [self.qTree insertObject:trapAnnotation];
        }
    }
    else
    {
        for (Traps *trap in kNETROADS_CONTEXT.arrayOfAllTraps)
        {
            double latitude = trap.lat;
            double longitude = trap.lon;

            double closePointLat = trap.closePointLat;
            double closePointLon = trap.closePointLon;

            DummyAnnotation *trapAnnotation = [[DummyAnnotation alloc] init];

            if (closePointLat != 0.0 || closePointLon != 0.0) trapAnnotation.coordinate = CLLocationCoordinate2DMake(closePointLat, closePointLon);
            else trapAnnotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);

            [self.qTree insertObject:trapAnnotation];
        }
    }
    NSLog(@"TOTAL NUMBER OF TRAPS (%s): %i", __PRETTY_FUNCTION__, success?fetchedObjects.count:[Netroads sharedInstance].arrayOfAllTraps.count);
}

附注: *致电initializeQuadTree后我正在初始化位置经理。 *在位置管理器中,我有一个dispatch_async包含整个代码。 *完成所有初始化后,代码的主要部分通过位置管理器didUpdateLocations发生。 *对于核心数据中的每一个使用,我正在生成新的NSManagedObjectConext,如下所示:

FOUNDATION_EXPORT NSManagedObjectContext *generateManagedObjectContext()
{
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init];
    context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator;
    return context;
}

1 个答案:

答案 0 :(得分:2)

[db deleteTrapsTable];
[dbat deleteTrapsTable];

创建表后删除了表