【发布时间】:2015-09-29 02:52:50
【问题描述】:
我有两个对象 GroupExercise > 练习,并且需要获取包含部分(标题 GroupExercise.name)和行(Exercise.name)的 tableView 请求 我如何使用 Magical Record 或 Core Data 获取两个实体
练习对象
@interface Exercise : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * timeRelax;
@property (nonatomic, retain) NSNumber * type;
@property (nonatomic, retain) NSNumber * uid;
@property (nonatomic, retain) NSNumber * uidGroup;
@property (nonatomic, retain) GroupExercise *groupEdge;
GroupExerciseObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSString * tagColor;
@property (nonatomic, retain) NSNumber * uid;
@property (nonatomic, retain) NSOrderedSet *exerciseEdge;
用代码保存对象
- (void)parseAndSaveJson:(id)json withCompleteBlock:(void (^)())completeBlock {
NSMutableArray *groupsArray = (NSMutableArray *) json;
NSLog(@"%@", json);
if (groupsArray != nil) {
NSArray *allEntities = [NSManagedObjectModel MR_defaultManagedObjectModel].entities;
[allEntities enumerateObjectsUsingBlock:^(NSEntityDescription *entityDescription, NSUInteger idx, BOOL *stop) {
[NSClassFromString([entityDescription managedObjectClassName]) MR_truncateAll];
}];
[MagicalRecord saveWithBlock:^(NSManagedObjectContext *localContext) {
for (int groupIndex = 0; groupIndex < [groupsArray count]; groupIndex++) {
GroupExercise *localGroup = [GroupExercise MR_createEntityInContext:localContext];
localGroup.name = groupsArray[groupIndex][LOCAL_GROUPS_NAME];
localGroup.tagColor = groupsArray[groupIndex][LOCAL_GROUPS_TAG_COLOR];
localGroup.uid = @([groupsArray[groupIndex][LOCAL_GROUPS_ID_GROUP] intValue]);
NSMutableArray *exerciseArray = (NSMutableArray *) groupsArray[groupIndex][LOCAL_GROUPS_EXERCISES];
NSMutableSet *set = [[NSMutableSet alloc] init];
for (int exerciseIndex = 0; exerciseIndex < [exerciseArray count]; exerciseIndex++) {
Exercise *exercise = [Exercise MR_createEntityInContext:localContext];
exercise.name = exerciseArray[exerciseIndex][EXERCISE_NAME];
exercise.uid = @([exerciseArray[exerciseIndex][LOCAL_EXERCISE_ID_EXERCISE] intValue]);
exercise.uidGroup = @([groupsArray[groupIndex][LOCAL_GROUPS_ID_GROUP] intValue]);
exercise.groupEdge = localGroup;
[set addObject:exercise];
}
[localGroup addExerciseEdge:set];
}
} completion:^(BOOL contextDidSave, NSError *error) {
completeBlock();
}];
}
}
并使用 FRC
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
_fetchedResultsController = [Exercise MR_fetchAllGroupedBy:@"groupEdge" withPredicate:nil sortedBy:@"uid" ascending:true];
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
如何使用 groupEdge.name 对部分进行排序?
【问题讨论】:
-
组在显示时会改变吗?你真的需要两个都取,还是只需要练习?
标签: ios objective-c core-data magicalrecord