所以我有一个具有几个属性的对象,我想将这些属性添加到 coredata 但是我使用的是我不太熟悉的 Mantle 框架。
我的对象(.h):
#import <Foundation/Foundation.h>
#import "RTModel.h"
@import CoreLocation;
@class RTPhoto;
@class RTContact;
@class RTUser;
@interface MyInteraction : RTModel <NSCopying, MTLJSONSerializing>
+ (NSManagedObject *)managedObjectWithIdentifier:(NSNumber *)identifier;
- (NSManagedObject *)managedObject;
@property (nonatomic, strong) NSNumber *latitude;
@property (nonatomic, strong) NSNumber *longitude;
@property (strong, nonatomic) RTUser *user;
@property (nonatomic, strong) NSNumber *createdByID;
@property (nonatomic, copy) NSString *createdByLabel;
@property (nonatomic, copy) NSString *interactedWithLabel;
@property (strong, nonatomic) NSString *publicShareURLString;
@property (nonatomic, strong) NSSet *photos;
- (void)addPhotosObject:(RTPhoto *)photo;
@end
我的对象(.m):
#import "OUTInteraction.h"
#import "RTComment.h"
#import "RTPhoto.h"
#import "RTUser.h"
#import "RTContact.h"
#import "OUTCoreDataController.h"
#import "OUTInteractionsController.h"
@interface MyInteraction () <UIActionSheetDelegate>
@end
@implementation MyInteraction
@synthesize identifier = _identifier;
@synthesize createdAt = _createdAt;
@synthesize updatedAt = _updatedAt;
- (void)deleteWithCompletion:(void (^)(NSError *))completion
{
NSManagedObject *managedObject = [self managedObject];
if (!managedObject) {
completion(nil);
};
[[[MyCoreDataController sharedController] persistenceController] deleteObject:managedObject
saveContextAndWait:YES
completion:^(NSError *error) {
completion(error);
}];
}
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return [[super JSONKeyPathsByPropertyKey] mtl_dictionaryByAddingEntriesFromDictionary: @{
@"createdByID" : @"created_by_id",
@"createdByLabel" : @"created_by_label",
@"interactedWithLabel" : @"interacted_with_label",
@"interactionType" : @"interaction_type",
@"latitude" : @"latitude",
@"longitude" : @"longitude",
@"formID" : @"form_id",
@"formEntries" : @"form_entries",
@"interactedWithCity" : @"interacted_with_city",
@"interactedWithRegion" : @"interacted_with_region",
@"publicShareURLString" : @"share_url",
@"photos" : @"images"
}];
}
#pragma mark - Photos
- (void)addPhotosObject:(RTPhoto *)photo
{
if (!photo) return;
NSMutableSet *mutablePhotos = [NSMutableSet setWithSet:self.photos];
[mutablePhotos addObject:photo];
self.photos = [mutablePhotos copy];
}
- (BOOL)hasPhotoToDisplay
{
if (!self.photos) return NO;
if ([[self.photos allObjects] count] > 0) return YES;
return NO;
}
#pragma mark - JSON Transformers
/// @note used by Mantle
+ (NSValueTransformer *)photosJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSArray *array) {
NSMutableSet *mutableSet = [NSMutableSet set];
[array enumerateObjectsUsingBlock:^(NSDictionary *JSON, NSUInteger idx, BOOL *stop) {
NSError *error = nil;
RTPhoto *item = [MTLJSONAdapter modelOfClass:[RTPhoto class]
fromJSONDictionary:JSON
error:&error];
if (error) DDLogError([error description], nil);
[mutableSet addObject:item];
}];
NSLog(@"mutable set");
return mutableSet;
} reverseBlock:^id(NSSet *set) {
NSLog(@"all objects");
return [set allObjects];
}];
}
/// @note used by Mantle
+ (NSValueTransformer *)commentsJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSArray *array) {
NSMutableSet *mutableSet = [NSMutableSet set];
[array enumerateObjectsUsingBlock:^(NSDictionary *JSON, NSUInteger idx, BOOL *stop) {
NSError *error = nil;
RTComment *item = [MTLJSONAdapter modelOfClass:[RTComment class]
fromJSONDictionary:JSON
error:&error];
if (error) DDLogError([error description], nil);
[mutableSet addObject:item];
}];
return mutableSet;
} reverseBlock:^id(NSSet *set) {
return [set allObjects];
}];
}
/// @note used by Mantle
+ (NSValueTransformer *)contactsJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSArray *array) {
NSMutableSet *mutableSet = [NSMutableSet set];
[array enumerateObjectsUsingBlock:^(NSDictionary *JSON, NSUInteger idx, BOOL *stop) {
NSError *error = nil;
RTComment *item = [MTLJSONAdapter modelOfClass:[RTContact class]
fromJSONDictionary:JSON
error:&error];
if (error) DDLogError([error description], nil);
[mutableSet addObject:item];
}];
return mutableSet;
} reverseBlock:^id(NSSet *set) {
return [set allObjects];
}];
}
/// @note used by Mantle
+ (NSValueTransformer *)formEntriesJSONTransformer
{
return [MTLValueTransformer reversibleTransformerWithForwardBlock:^id(NSArray *entryDictionaries) {
NSMutableSet *set = [NSMutableSet set];
[entryDictionaries enumerateObjectsUsingBlock:^(NSDictionary *entryDict, NSUInteger idx, BOOL *stop) {
NSError *error = nil;
RTInteractionFormEntry *entry = [MTLJSONAdapter modelOfClass:[RTInteractionFormEntry class]
fromJSONDictionary:entryDict
error:&error];
[set addObject:entry];
}];
return set;
} reverseBlock:^id(NSSet *set) {
NSMutableArray *array = [NSMutableArray array];
[set enumerateObjectsUsingBlock:^(RTInteractionFormEntry *entry, BOOL *stop) {
[array addObject:[entry jsonDictionary]];
}];
return array;
}];
}
/// @note used by Mantle
+ (NSValueTransformer *)userJSONTransformer
{
return [MTLValueTransformer mtl_JSONDictionaryTransformerWithModelClass:[RTUser class]];
}
/// @note used by Mantle
+ (NSValueTransformer *)interactionTypeJSONTransformer
{
return [NSValueTransformer mtl_valueMappingTransformerWithDictionary:@{
@"email" : @(kRTInteractionTypeEmail),
@"check_in" : @(kRTInteractionTypeCheckIn),
@"note" : @(kRTInteractionTypeNote),
@"meeting" : @(kRTInteractionTypeMeeting)
}];
}
#pragma mark - Core Data
+ (NSString *)managedObjectEntityName
{
return @"Interaction";
}
+ (NSSet *)propertyKeysForManagedObjectUniquing
{
return [NSSet setWithArray:@[@"identifier"]];
}
+ (NSDictionary *)managedObjectKeysByPropertyKey
{
return [[super managedObjectKeysByPropertyKey] mtl_dictionaryByAddingEntriesFromDictionary:@{
@"metadata" : [NSNull null],
@"identifier" : @"interactionIdentifier",
}];
}
+ (NSDictionary *)relationshipModelClassesByPropertyKey
{
return [[super relationshipModelClassesByPropertyKey] mtl_dictionaryByAddingEntriesFromDictionary:@{
@"comments" : [RTComment class],
@"formEntries" : [RTInteractionFormEntry class],
@"photos" : [RTPhoto class],
@"contacts" : [RTContact class],
@"user" : [RTUser class]
}];
}
#pragma mark - Actions
- (void)delete
{
[[MyInteractionsController controller] deleteInteraction:self
success:^{
} failure:^(NSError *error) {
DDLogError([error description], nil);
}];
}
+ (NSManagedObject *)managedObjectWithIdentifier:(NSNumber *)identifier
{
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:[MyInteraction managedObjectEntityName]];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"interactionIdentifier == %@", identifier];
fetchRequest.fetchLimit = 1;
NSManagedObjectContext *managedObjectContext = [[MyCoreDataController sharedController] managedObjectContext];
NSError *error = nil;
NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest
error:&error];
NSLog(@"Results: %@", results);
if (error) {
DDLogError(@"Error fetching managed object: %@", [error description]);
}
return [results firstObject];
}
- (NSManagedObject *)managedObject
{
return [MyInteraction managedObjectWithIdentifier:self.identifier];
}
- (void)mergeValuesForKeysFromManagedObject:(NSManagedObject *)managedObject
{
if ([managedObject valueForKey:@"photos"]) {
NSMutableSet *combinedPhotos = [NSMutableSet setWithSet:self.photos];
for (NSManagedObject *photoManagedObject in [managedObject valueForKey:@"photos"]) {
RTPhoto *photo = [MTLManagedObjectAdapter modelOfClass:[RTPhoto class]
fromManagedObject:photoManagedObject
error:nil];
if (photo.identifier || photo.localImageData || photo.imageDataPendingUpload) {
[combinedPhotos addObject:photo];
}
}
self.photos = [combinedPhotos copy];
}
}
@end
基本上,我在通过 Mantle 将整个对象添加到 CoreData 时遇到的问题是,除了到达作为 NSSet 的 photos 属性外,所有内容都会被添加,它只添加一个对象,通常是最后一个。
这是使用 Mantle(在另一个文件中)将对象添加到上下文中的情况:
[MTLManagedObjectAdapter managedObjectFromModel:interaction
insertingIntoContext:self.context
error:&coreDataError];
如果有人知道为什么在“照片”键下只添加了一个照片对象。我不熟悉地幔如何处理许多关系以及如何添加所有孩子。谢谢