RESKit:创建重复的对象 [英] RESKit: Duplicate objects are created

查看:130
本文介绍了RESKit:创建重复的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提取后,数据库中出现重复。



下面是映射和提取代码:

  +(RKEntityMapping *)userMapping:(RKEntityMapping *)userMapping 
{
[userMapping addAttributeMappingsFromDictionary:@ {
@userid:@userid
@firstName:@firstName,
@lastName:@lastName,
}
userMapping.identificationAttributes = @ [@userid];

return userMapping;
}

提取代码:

  AppDelegate * appDelegate =(AppDelegate *)[[UIApplication sharedApplication] delegate]; 
self.objectManager = [self getObjectManager];

self.objectManager.managedObjectStore = appDelegate.managedObjectStore;
self.managedObjectContext = self.objectManager.managedObjectStore.mainQueueManagedObjectContext;

[RKObjectManager sharedManager] .requestSerializationMIMEType = RKMIMETypeJSON;

RKEntityMapping * userMapping = [RKEntityMapping mappingForEntityForName:@UserinManagedObjectStore:self.objectManager.managedObjectStore];
userMapping = [RESTMappingProvider userMapping:userMapping];

NSIndexSet * statusCodeSet = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor * responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:userMapping
method:RKRequestMethodGET
pathPattern:nil
keyPath:@findUserstatusCodes:statusCodeSet];

NSMutableURLRequest * request = [self.objectManager.HTTPClient requestWithMethod:@GET
path:@/ findUser
parameters:@ {@userid:userSearch
}];

//request.cachePolicy = NSURLRequestReloadIgnoringCacheData;

[self.objectManager.HTTPClient registerHTTPOperationClass:[AFHTTPRequestOperation class]];

RKManagedObjectRequestOperation * operation = [[RKManagedObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@ [responseDescriptor]];
operation.managedObjectContext = self.objectManager.managedObjectStore.mainQueueManagedObjectContext;
operation.savesToPersistentStore = NO;

[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation * operation,RKMappingResult * mappingResult){
NSError * error;
for(User * foundUser in mappingResult.array)
{
foundUser.lastUpdated = [NSDate date];
}
if([self.managedObjectContext saveToPersistentStore:& error])
{
NSLog(@******* User OBJECTS SAVED ***** *****);
}

}失败:^(RKObjectRequestOperation * operation,NSError * error){
});

}];

[操作开始];
[operation waitUntilFinished];
}
}

LOG:

  2014-07-27 14:25:48.756 App [36854:5b3b] W restkit.core_data:RKManagedObjectMappingOperationDataSource.m:243使用nil管理对象执行受管对象映射cache:
无法通过标识属性更新现有对象实例。可能会创建重复的对象。
2014-07-27 14:25:48.756 App [36854:3803] D restkit.object_mapping:RKPropertyInspector.m:130类'User'的缓存属性检查:{
email = {
isPrimitive = 0;
keyValueCodingClass = NSString;
name = email;
};
firstName = {
isPrimitive = 0;
keyValueCodingClass = NSString;
name = firstName;
};
lastName = {
isPrimitive = 0;
keyValueCodingClass = NSString;
name = lastName;
};
lastUpdated = {
isPrimitive = 0;
keyValueCodingClass = NSDate;
name = lastUpdated;
};
userid = {
isPrimitive = 0;
keyValueCodingClass = NSString;
name = userid;
};
}
2014-07-27 14:25:48.757 App [36854:5b3b] D restkit.object_mapping:RKMapperOperation.m:231请求映射源对象{
firstName = Lois;
lastName = Lane;
userid =lois.lane;
},映射< RKEntityMapping:0x12d78e80 objectClass = User propertyMappings =(
< RKAttributeMapping:0x12d819d0 userid => userid>,
< RKAttributeMapping:0x12d85f70 lastName => lastName>,
< RKAttributeMapping:0x12d72a10 firstName => firstName>,
)>

2014-07-27 14:25:49.476 App [36854:3803] W restkit.core_data:RKManagedObjectMappingOperationDataSource.m:243使用nil被管对象缓存执行受管对象映射:
Unable以通过标识属性更新现有对象实例。可能会创建重复的对象。
2014-07-27 14:25:49.477 App [36854:3803] D restkit.object_mapping:RKMapperOperation.m:231请求映射源对象{
firstName = Lois;
lastName = Lane;
userid =lois.lane;
}与映射< RKEntityMapping:0xd6c17a0 objectClass = User propertyMappings =(
< RKAttributeMapping:0xd6b6ed0 userid => userid>,
< RKAttributeMapping:0xd6c86b0 lastName => lastName>,
< RKAttributeMapping:0xd6c1560 firstName => firstName>,
)>]

数据库:





编辑1

   - (RKManagedObjectStore *)setupCoreDataWithRESTKit 
{
NSError * error;
NSURL * modelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@AppofType:@momd]];
NSManagedObjectModel * managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] mutableCopy];
self.managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];

[self.managedObjectStore createPersistentStoreCoordinator];

NSArray * searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);

NSString * documentPath = [searchPaths objectAtIndex:0];
NSPersistentStore * persistentStore = [self.managedObjectStore addSQLitePersistentStoreAtPath:[NSString stringWithFormat:@%@ / App.sqlite,documentPath] fromSeedDatabaseAtPath:nil withConfiguration:nil options:[self optionsForSqliteStore] error:&
NSAssert(persistentStore,@无法添加持久存储,错误:%@,错误);

if(!persistentStore){
NSLog(@无法添加持久存储:%@,错误);
}

[self.managedObjectStore createManagedObjectContexts];

return self.managedObjectStore;
}


解决方案

。这就是RestKit搜索和查找现有对象的方式,这是避免重复的机制。有2种类型或缓存,但通常要使用内存缓存(与提取缓存相反),因为它更快。



创建并设置缓存:

  self.managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectSyore.persistentStoreManagedObjectContext]; 


Duplicates appear in the database after fetching.

Below are the mapping and the fetch code:

+(RKEntityMapping *)userMapping:(RKEntityMapping *)userMapping
{
    [userMapping addAttributeMappingsFromDictionary:@{
                                                      @"userid" : @"userid",
                                                      @"firstName" : @"firstName",
                                                      @"lastName" : @"lastName",
                                                          }];
    userMapping.identificationAttributes = @[@"userid"];

    return userMapping;
}

Fetch Code:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.objectManager = [self getObjectManager];

self.objectManager.managedObjectStore = appDelegate.managedObjectStore;
self.managedObjectContext = self.objectManager.managedObjectStore.mainQueueManagedObjectContext;

[RKObjectManager sharedManager].requestSerializationMIMEType = RKMIMETypeJSON;

RKEntityMapping *userMapping = [RKEntityMapping mappingForEntityForName:@"User" inManagedObjectStore:self.objectManager.managedObjectStore];
        userMapping = [RESTMappingProvider userMapping:userMapping];

NSIndexSet *statusCodeSet = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
        RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:userMapping
                                                                                                method:RKRequestMethodGET
                                                                                           pathPattern:nil
                                                                                               keyPath:@"findUser" statusCodes:statusCodeSet];

NSMutableURLRequest *request = [self.objectManager.HTTPClient requestWithMethod:@"GET"
                                                                                   path:@"/findUser"
                                                                             parameters:@{@"userid": userSearch
                                                                                          }];

//request.cachePolicy = NSURLRequestReloadIgnoringCacheData;

[self.objectManager.HTTPClient  registerHTTPOperationClass:[AFHTTPRequestOperation class]];

RKManagedObjectRequestOperation *operation = [[RKManagedObjectRequestOperation alloc]initWithRequest:request responseDescriptors:@[responseDescriptor]];
operation.managedObjectContext = self.objectManager.managedObjectStore.mainQueueManagedObjectContext;
    operation.savesToPersistentStore = NO;

[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
        NSError *error;
        for (User *foundUser in mappingResult.array)
        {
            foundUser.lastUpdated = [NSDate date];
        }
        if ([self.managedObjectContext saveToPersistentStore:&error])
        {
            NSLog (@"******* User OBJECTS SAVED **********");
        }

     } failure:^(RKObjectRequestOperation *operation, NSError *error) {
     });

     }];

        [operation start];
        [operation waitUntilFinished];
    }
}

LOG:

2014-07-27 14:25:48.756 App[36854:5b3b] W restkit.core_data:RKManagedObjectMappingOperationDataSource.m:243 Performing managed object mapping with a nil managed object cache:
Unable to update existing object instances by identification attributes. Duplicate objects may be created.
2014-07-27 14:25:48.756 App[36854:3803] D restkit.object_mapping:RKPropertyInspector.m:130 Cached property inspection for Class 'User': {
    email =     {
        isPrimitive = 0;
        keyValueCodingClass = NSString;
        name = email;
    };
    firstName =     {
        isPrimitive = 0;
        keyValueCodingClass = NSString;
        name = firstName;
    };
    lastName =     {
        isPrimitive = 0;
        keyValueCodingClass = NSString;
        name = lastName;
    };
    lastUpdated =     {
        isPrimitive = 0;
        keyValueCodingClass = NSDate;
        name = lastUpdated;
    };
    userid =     {
        isPrimitive = 0;
        keyValueCodingClass = NSString;
        name = userid;
    };
}
2014-07-27 14:25:48.757 App[36854:5b3b] D restkit.object_mapping:RKMapperOperation.m:231 Asked to map source object {
    firstName = Lois;
    lastName = Lane;
    userid = "lois.lane";
} with mapping <RKEntityMapping:0x12d78e80 objectClass=User propertyMappings=(
    "<RKAttributeMapping: 0x12d819d0 userid => userid>",
    "<RKAttributeMapping: 0x12d85f70 lastName => lastName>",
    "<RKAttributeMapping: 0x12d72a10 firstName => firstName>",
)>

2014-07-27 14:25:49.476 App[36854:3803] W restkit.core_data:RKManagedObjectMappingOperationDataSource.m:243 Performing managed object mapping with a nil managed object cache:
Unable to update existing object instances by identification attributes. Duplicate objects may be created.
2014-07-27 14:25:49.477 App[36854:3803] D restkit.object_mapping:RKMapperOperation.m:231 Asked to map source object {
    firstName = Lois;
    lastName = Lane;
    userid = "lois.lane";
} with mapping <RKEntityMapping:0xd6c17a0 objectClass=User propertyMappings=(
    "<RKAttributeMapping: 0xd6b6ed0 userid => userid>",
    "<RKAttributeMapping: 0xd6c86b0 lastName => lastName>",
    "<RKAttributeMapping: 0xd6c1560 firstName => firstName>",
)>]

Database:

How can I avoid duplicates?

EDIT 1

- (RKManagedObjectStore *)setupCoreDataWithRESTKit
{
    NSError * error;
    NSURL * modelURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"App" ofType:@"momd"]];
    NSManagedObjectModel * managedObjectModel = [[[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL] mutableCopy];
    self.managedObjectStore = [[RKManagedObjectStore alloc] initWithManagedObjectModel:managedObjectModel];

    [self.managedObjectStore createPersistentStoreCoordinator];

    NSArray * searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString * documentPath = [searchPaths objectAtIndex:0];
    NSPersistentStore * persistentStore = [self.managedObjectStore addSQLitePersistentStoreAtPath:[NSString stringWithFormat:@"%@/App.sqlite", documentPath] fromSeedDatabaseAtPath:nil withConfiguration:nil options:[self optionsForSqliteStore] error:&error];
    NSAssert(persistentStore, @"Failed to add persistent store with error: %@", error);

    if(!persistentStore){
        NSLog(@"Failed to add persistent store: %@", error);
    }

    [self.managedObjectStore createManagedObjectContexts];

    return self.managedObjectStore;
}

解决方案

You need to create a cache. This is how RestKit searches for and finds existing objects, which is the mechanism for avoiding duplicates. There are 2 types or cache, but you usually want to use the memory cache (as opposed to the fetch cache) as it is faster.

Create and set the cache with:

self.managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:managedObjectSyore.persistentStoreManagedObjectContext];

这篇关于RESKit:创建重复的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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