ios - NSManagedObjectContext 只工作了几次,然后就停止工作了

标签 ios objective-c core-data

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

1) 我正在使用核心数据保存到 NSManagedObjects:CoreDataTrap & CoreDataAllTraps。 第一次,我解析一个大的 xml,然后转换为数组,然后将详细信息添加到 CoreDataAllTraps,据我所知,这个操作进行得很顺利,因为我做了一个日志。

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

这些函数为我提供了正确的记录数。 3) 然后初始化一些变量。

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

这会返回我的断言错误。

Error: fetchedObjects have no records.

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;
}

最佳答案

[db deleteTrapsTable];
[dbat deleteTrapsTable];

创建后删除的表

关于ios - NSManagedObjectContext 只工作了几次,然后就停止工作了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21855893/

相关文章:

ios - 切换 View Controller 后 uitextfield 不更新

iphone - PhoneGap + Landscape : SplashScreen Loads Properly, 然后在闪烁和消失之前短暂旋转

ios - 如何在 AVQueuePlayer 中循环播放声音队列?

ios - 无法在 ViewController 之间移动

ios - UIApplication 的 `beginIgnoringInteractionEvents` 不工作

ios - Xcode应用程序崩溃且没有错误

ios - 如何使用 Swift 水平翻转 UIImage?

ios - 有没有一种方法可以使用 Objective-C 从 PNG 文件中提取自定义元数据?

ios - 核心数据父实体

ios - 没有错误日志的核心数据获取请求崩溃