RESKit:创建了重复的对象

Posted

技术标签:

【中文标题】RESKit:创建了重复的对象【英文标题】:RESKit: Duplicate objects are created 【发布时间】:2014-07-27 21:40:34 【问题描述】:

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

下面是映射和获取代码:

+(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:@"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];
    

日志:

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>",
)>]

数据库:

如何避免重复?

编辑 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;

【问题讨论】:

您是否正在创建托管对象缓存? 我用我设置 Core Data 的方式更新了它。 【参考方案1】:

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

使用以下命令创建和设置缓存:

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

【讨论】:

我在setupCoreDataWithRESTKit 方法中添加了行:self.managedObjectStore.managedObjectCache = [[RKInMemoryManagedObjectCache alloc] initWithManagedObjectContext:self.managedObjectStore.persistentStoreManagedObjectContext];,但是当我再次获取时,dups 仍然出现在 .sqlite 文件中。我获取的越多,出现的副本就越多。我希望任何后续提取都应该更新现有对象。 好的,所以我还必须添加以下行:operation.managedObjectCache = appDelegate.managedObjectStore.managedObjectCache; 您能否调整答案。谢谢! 顺便说一句,如果其中一个属性已更新,RESTKit 将更新对象,对吗? RestKit 比较找到的对象的变化并且只更新那些已经变化的东西。

以上是关于RESKit:创建了重复的对象的主要内容,如果未能解决你的问题,请参考以下文章

ResKit iOS - 为同一个元素注册多个类

RESKit:无响应描述符

没有关键路径的 Reskit 映射数组

将 ResKit 集成到现有的 Core Data 应用程序中

ResKit:临时 NSManagedObjects

Jquery循环重复创建相同的对象