NSManagedObjectContext只能运行几次,然后停止工作 [英] NSManagedObjectContext work well only a few times, then it stops working

查看:53
本文介绍了NSManagedObjectContext只能运行几次,然后停止工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



1)我正在使用核心数据保存到 NSManagedObjects CoreDataTrap & CoreDataAllTraps
第一次,我解析一个较大的xml,然后转换为数组,然后将详细信息添加到 CoreDataAllTraps ,此操作进展顺利,因为我知道



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



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



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




错误:fetchedObjects没有记录。


5)然后,使用核心数据的所有其他功能当然都会返回错误,因为没有数据。



相关(编号)代码:

  1:
---
-(无效) addOrUpdateTrap :(陷阱*)trapObject
{
NSManagedObjectContext * context = generateManagedObjectContext();

int trapID = trapObject.getTrapID;
CoreDataAllTraps * trapEntity = nil;
NSError *错误=无;

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(结果==零)
{
//处理错误
}
else if(results.count == 0)
{
//无需更新,添加新陷阱
//创建新记录(行)
trapEntity = [NSEntityDescription insertNewObjectForEntityForName:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
}
其他
{
trapEntity = results [0]; // ID只能有一个对象。
}


if(trapEntity!= nil)
{
//设置新对象或现有对象的属性...

// 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];
//所有属性等...


error = nil;
if([context save:& error] == NO){
NSLog(@%s错误保存:%@ \n%@,__ PRETTY_FUNCTION __,error.localizedDescription,error.userInfo );
}
else {
[重置上下文];
}
}
}

2:
-
-(void)saveArray:(NSArray *)array
{
kNETROADS_CONTEXT.arrayOfAllTraps = self.arrayOfAllTraps = array.mutableCopy;
NSLog(@陷阱总数:%d,self.arrayOfAllTraps.count);

NSManagedObjectContext *上下文= generateManagedObjectContext();

NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *实体= [NSEntityDescription实体名称:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *错误=无;
NSArray * fetchedObjects = [上下文executeFetchRequest:fetchRequest错误:&错误];
NSLog(@ TrapService-fetchedObjects.count:%d,fetchedObjects.count);

if(fetchedObjects == nil || fetchedObjects.count == 0){
NSLog(@ saveArray-localizedDescription:%@,userInfo:%@,error.localizedDescription,错误。用户信息);
}

[self readArray];
}

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

NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *实体= [NSEntityDescription实体名称:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *错误=无;
NSArray * fetchedObjects = [上下文executeFetchRequest:fetchRequest错误:&错误];
NSLog(@ readArray-fetchedObjects.count:%d,fetchedObjects.count);

if(fetchedObjects == nil || fetchedObjects.count == 0){
NSLog(@ readArray-localizedDescription:%@,userInfo:%@,error.localizedDescription,错误。用户信息);
}
}

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

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

kRECEIVER_CONTEXT.db = [[数据库分配] 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新];
self.mLastLocation = [CLLocation新];
self.globalLocation = [CLLocation新];
self.lastGlobalLocation = [CLLocation新];
self.myLocations = [[NSMutableArray alloc] init];
self.accuracy = @ N / A;
self.closeTrap = [[陷阱分配] init];

self.notification = [NSNotificationCenter defaultCenter];
// // [self.notification addObserver:self选择器:@selector(onReceive :)名称:kSend_To_Receiver_Notification对象:nil];
}

4:
---

-(void)initializeQuadTree
{
self.qTree = [[ QuadTree alloc] init];
BOOL成功=是;

NSManagedObjectContext *上下文= generateManagedObjectContext();

NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *实体= [NSEntityDescription实体名称:kCORE_DATA_ALL_TRAPS_ENTITY inManagedObjectContext:context];
[fetchRequest setEntity:entity];

NSError *错误=无;
NSArray * fetchedObjects = [上下文executeFetchRequest:fetchRequest错误:&错误];
if(fetchedObjects == nil || fetchedObjects.count == 0)
{
NSLog(@ initializeQuadTree-localizedDescription:%@,userInfo:%@,error.localizedDescription,错误。用户信息);
成功=否;
}

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

NSAssert(fetchedObjects!= nil,@错误:fetchedObjects = nil);
NSAssert(fetchedObjects.count> 0,@错误:fetchedObjects没有记录。);

如果成功,则
{
for(CoreDataAllTraps * fetchedObjects中的陷阱)
{
double latitude = trap.lat.doubleValue;
double经度= 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(纬度,经度);

[self.qTree insertObject:trapAnnotation];
}
}
else
{
for(陷阱* 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(纬度,经度);

[self.qTree insertObject:trapAnnotation];
}
}
NSLog(@陷阱总数(%s):%i,__ PRETTY_FUNCTION__,成功?fetchedObjects.count:[Netroads sharedInstance] .arrayOfAllTraps.count);
}

旁注:
*呼叫后initializeQuadTree 我正在初始化位置管理器。
*在位置管理器中,我有一个 dispatch_async ,将整个代码包装在其中。
*完成所有初始化后,代码的主要部分通过位置管理器 didUpdateLocations 进行。
*对于核心数据中的每一次使用,我都会像这样生成新的NSManagedObjectConext:

  FOUNDATION_EXPORT NSManagedObjectContext * generateManagedObjectContext ()
{
NSManagedObjectContext * context = [[NSManagedObjectContext alloc] init];
context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator;
返回上下文;
}


解决方案

  [db deleteTrapsTable]; 
[dbat deleteTrapsTable];

在创建表后将其删除


After I tried to ask twice and explain myself, I did a dig and I think I can now explain my problem better:

1) I'm using core data to save to NSManagedObjects: CoreDataTrap & CoreDataAllTraps. First time, I'm parsing a large xml and then convert to array and then add the details to CoreDataAllTraps, this operation going well as I know because I did a log.

2) Then, Just for the test, I'm fetching all of the records and log the total number of them.

Those functions give me the correct number of records. 3) Then just initializing a few variables.

4) Then initializing my quad tree.

Which gives me back my assertion error.

Error: fetchedObjects have no records.

5) Then, all the rest of the functions that using core data gives me error back of course, because there is no data.

Relevant (numbered) code:

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

Side notes: * After calling initializeQuadTree i'm initializing the location manager. * In location manager I've a dispatch_async that wrap the whole code inside. * After I done with all initializing, the main of the code happens via location manager didUpdateLocations. * For each and every using in core data I'm generating new NSManagedObjectConext like this:

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

解决方案

[db deleteTrapsTable];
[dbat deleteTrapsTable];

The table deleted after you create it

这篇关于NSManagedObjectContext只能运行几次,然后停止工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆