또 다른 question 코어 데이터에 의해 뒷받침되는 UITableView에서 삽입 행 추가에 관한 내 NSFetchedResultsController는 내 UITableView의 별도 섹션에 가져 오는 각 개체를 할당하는 언급했다. 이것은 단순히 기본 동작이라고 가정했지만 Marcus S. Zarra는 컨트롤러 또는 데이터 소스 대리자 방법의 구성에 문제가있을 수 있다고했습니다. 내 코드는 Apple docs 및 수많은 자습서에서 가져온 일부로 Frankenstein과 조금 비슷하다고 느낍니다.NSFetchedResultsController가 가져온 개체를 여러 개의 UITableView 섹션에 할당하는 이유는 무엇입니까?
#import <UIKit/UIKit.h>
#import "RubricAppDelegate.h"
@interface ClassList : UITableViewController {
NSMutableArray *classList;
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
}
@property(nonatomic,retain) NSMutableArray *classList;
@property(nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
@property(nonatomic, retain) NSManagedObjectContext *managedObjectContext;
- (IBAction) grade:(id)sender;
@end
내 구현 파일 더미 테스트 데이터의 무리가 포함되어 다음과 같이
내 테이블 뷰 컨트롤러의 헤더입니다)이 때문에 부드러운 주시기 바랍니다, 코어 데이터를 사용하여 내 첫 번째 프로그램 내 처음이다. 코어 데이터 객체를 인스턴스화하는 데 잘못된 메소드를 사용하고있는 경우를 대비하여 포함했습니다. 기본적으로 내 NSFetchedResultsController가 이 아니고이 내 개체 (이 경우 myClass의 인스턴스)를 별도의 섹션으로 반환해야하는지 알고 싶습니다. 그렇다면 그 문제를 만들기 위해 무엇을하고 있습니까?
현재 궁극적 인 목표는 내 테이블 상단에 삽입 셀을 추가하는 것입니다 (하단에 배치하는 것이 "표준"이라고 알고 있지만 앱에서 보이는 방식이 마음에 듭니다. 그것은 다른 방향으로). 당신은 나의 -tableView:editingStyleForRowAtIndexPath:
가 섹션 0의 셀 스타일을 삽입하도록 설정했음을 알게 될 것이다. 물론 셀 0 대신 셀 1에서 myClass.classTitle의 목록을 시작하는 방법을 알아야한다. 자체 섹션에 할당 된 객체는 정상입니다).
가 여기 내 구현 파일입니다
#import "ClassList.h"
#import "ClassRoster.h"
#import "RubricAppDelegate.h"
#import "Student.h"
#import "myClass.h"
@implementation ClassList
@synthesize classList;
@synthesize fetchedResultsController;
@synthesize managedObjectContext;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.editing = YES;
RubricAppDelegate *appDelegate = (RubricAppDelegate *)[[UIApplication sharedApplication] delegate];
managedObjectContext = [appDelegate managedObjectContext];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"myClass" inManagedObjectContext:managedObjectContext];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entity];
//test data
myClass *newClass = (myClass *) [NSEntityDescription insertNewObjectForEntityForName:@"myClass" inManagedObjectContext:managedObjectContext];
newClass.classTitle = @"UFDN 1000";
NSNumber *ID = [NSNumber numberWithInt:1];
newClass.classID = ID;
Student *newStudent = (Student *) [NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:managedObjectContext];
newStudent.classID = ID;
newStudent.studentName = @"Andy Albert";
newStudent.studentUsername = @"albera";
[newClass addStudentsObject:newStudent];
newStudent.classID = ID;
newStudent.studentName = @"Bob Dole";
newStudent.studentUsername = @"doleb";
[newClass addStudentsObject:newStudent];
newStudent.classID = ID;
newStudent.studentName = @"Chris Hanson";
newStudent.studentUsername = @"hansoc";
[newClass addStudentsObject:newStudent];
myClass *newClass2 = (myClass *) [NSEntityDescription insertNewObjectForEntityForName:@"myClass" inManagedObjectContext:managedObjectContext];
newClass2.classTitle = @"UFDN 3100";
ID = [NSNumber numberWithInt:2];
newClass2.classID = ID;
newStudent.classID = ID;
newStudent.studentName = @"Danny Boy";
newStudent.studentUsername = @"boyd";
[newClass2 addStudentsObject:newStudent];
newStudent.classID = ID;
newStudent.studentName = @"James Matthews";
newStudent.studentUsername = @"matthj";
[newClass2 addStudentsObject:newStudent];
newStudent.classID = ID;
newStudent.studentName = @"Aaron Todds";
newStudent.studentUsername = @"toddsa";
[newClass2 addStudentsObject:newStudent];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"classID" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
NSError *error;
fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:@"classTitle" cacheName:nil];
[fetchedResultsController performFetch:&error];
UIBarButtonItem *gradeButton = [[UIBarButtonItem alloc]
initWithTitle:@"Grade"
style:UIBarButtonItemStylePlain
target:self
action:@selector(grade:)];
self.navigationItem.rightBarButtonItem = gradeButton;
[gradeButton release];
}
- (IBAction) grade:(id)sender {
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(@"Number of sections = %d", [[fetchedResultsController sections] count]);
return ([[fetchedResultsController sections] count]);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
id <NSFetchedResultsSectionInfo> myClass = [[fetchedResultsController sections] objectAtIndex:section];
NSLog(@"Number of classes = %d", [myClass numberOfObjects]);
return [myClass numberOfObjects];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
myClass *theClass = [fetchedResultsController objectAtIndexPath:indexPath];
NSLog(@"Class name is: %@", theClass.classTitle);
cell.textLabel.text = theClass.classTitle;
}
return cell;
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0) {
return UITableViewCellEditingStyleInsert;
}
else return UITableViewCellEditingStyleDelete;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
myClass *result = (myClass *)[fetchedResultsController objectAtIndexPath:indexPath];
[managedObjectContext deleteObject:result];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
}
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
*/
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[classList release];
[super dealloc];
}
@end
내 RubricAppDelegate 등 핵심 데이터 NSManagedObjectContext, NSPersistentStoreCoordinator을 설정하기위한 애플의 문서 본질적으로 동일하지만, 당신이 거기에 문제가있을 수 있습니다 생각한다면, 그냥 알려주세요. 나는 그것을 게시 할 것입니다.
편집 : 각 개체가 다른 섹션에 할당된다는 것을 알고있는 두 가지 이유를 언급하는 것을 잊어 버렸습니다.
1) NSLog(@"Number of sections = %d", [[fetchedResultsController sections] count]);
내 -numberOfSectionsInTableView:
은 내가 가지고있는 myClass 객체의 수를 반환합니다.
2) -numberOfSectionsInTableView:
을 1로 설정하면 내 테이블에 하나의 개체 만 표시되고 나머지는 잘립니다.
정말 쉬웠습니다 :) Thanks TechZen! – Spindler