我有2个实体 - "老师"和"主题",和2个控制器,AddSubject和主题管理器。实体"主题"有一段关系"老师"。在我的AddSubjectController中,我添加一个主题,从UIPickerView中选择一个教师
Subjects *subject = [NSEntityDescription insertNewObjectForEntityForName:@"Subjects" inManagedObjectContext:self.managedObjectContext];
int selectedRow = [teacherPickerView selectedRowInComponent:0];
subject.name = nameOfSubjectTextField.text;
subject.article = notesTextView.text;
subject.teacher = [teacherForSubjectArray objectAtIndex:selectedRow];
teacherForSubjectArray是一个包含Core Data
对象的数组- (NSArray *)takeTeacherForSubject {
managedObjectContext = [AppDelegate sharedDelegate].managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *description = [NSEntityDescription entityForName:@"Teacher" inManagedObjectContext:
managedObjectContext];
[request setEntity:description];
NSError *requestError = nil;
teacherForSubjectArray = [[self.managedObjectContext executeFetchRequest:request error:&requestError] mutableCopy];
if (requestError) {
NSLog(@"%@" , [requestError localizedDescription]);
}
return teacherForSubjectArray;
}
然后在我的SubjectManager中我试图在UITable View中显示这些数据,然后从核心数据中取出
- (NSArray *)takeSubjectFromCoreData {
managedObjectContext = [AppDelegate sharedDelegate].managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *description = [NSEntityDescription entityForName:@"Subjects" inManagedObjectContext:
managedObjectContext];
[request setEntity:description];
NSError *requestError = nil;
subjectsResultArray = [[self.managedObjectContext executeFetchRequest:request error:&requestError] mutableCopy];
if (requestError) {
NSLog(@"%@" , [requestError localizedDescription]);
}
NSLog(@"%@", subjectsResultArray);
return subjectsResultArray;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
Subjects *objectSubject = [subjectsResultArray objectAtIndex:(long)indexPath.row];
UITableViewCell *cell = [subjectsTableView dequeueReusableCellWithIdentifier:@"subjectCell" forIndexPath:indexPath];
NSString *subjectName = [NSString stringWithFormat:@"%@", [objectSubject valueForKey:@"name"]];
NSString *teacherOfSubject = [NSString stringWithFormat:@"%@", objectSubject.teacher];
cell.textLabel.text = subjectName;
cell.detailTextLabel.text = teacherOfSubject;
return cell;
}
但是teacherOfSubject有一个问题,我得到的不是当前值,而是一个路径,或者NSmanagedObject而不是我需要的值,比如
0x7a6806d0 x-coredata:// 6DB0CDAF-5C8C-4128-BB43-D0EC10EA41D6 / Teacher / p2。
我知道答案应该很简单,但我厌倦了尝试自己解决。
答案 0 :(得分:0)
这一行:
NSString *teacherOfSubject = [NSString stringWithFormat:@"%@", objectSubject.teacher];
为您提供主题的教师关系的字符串表示 - 即对对象的引用,而不是对特定属性的引用。您可能想要的是引用教师的某些属性,例如名称。假设您已为两个实体创建了子类,则可以使用:
NSString *teacherOfSubject = [NSString stringWithFormat:@"%@", objectSubject.teacher.name];
如果没有,请使用:
NSManagedObject *teacher = [objectSubject valueForKey:@"teacher"];
NSString *teacherOfSubject = [NSString stringWithFormat:@"%@", [teacher valueForKey:@"name"];
显然修改name
以匹配您希望使用的任何属性。