请帮助我解决这个问题(我现在变得疯狂了!),我的项目正在将数据正确保存到coredata中的sqlite数据库,正如在SQLite图形管理器中检查的那样,但我似乎无法显示它在表视图中,我需要在viewController中使用我的表(小表不是整个屏幕),
如果您感到慷慨,请查看我的小样本项目 Here Thankyou!
这里是* viewcontroller.h的代码
(请注意我为表视图包含了一个IBoutlet,因为tableView不是UIViewController中的实例!)这样做是否正确? 另外,我得到7个警告,我称之为tableView> 'tableView'的本地声明隐藏了实例变量
#import <UIKit/UIKit.h>
@interface CoreDataEnsaViewController : UIViewController
<UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate> //va controller delegate??
{
UITextField *name;
UITextField *address;
UITextField *phone;
UILabel *status;
//la table
//NSMutableArray *array;
//la tabla??
UITableView *tableView;
NSFetchedResultsController *_fetchedResultsController;
NSManagedObjectContext *_context;
}
@property (nonatomic, retain) IBOutlet UITextField *name;
@property (nonatomic, retain) IBOutlet UITextField *address;
@property (nonatomic, retain) IBOutlet UITextField *phone;
@property (nonatomic, retain) IBOutlet UILabel *status;
@property (nonatomic, retain) IBOutlet UITableView *tableView;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, retain) NSManagedObjectContext *context;
- (IBAction) saveData;
- (IBAction) findContact;
- (IBAction) showbtn:(id) sender;
@end
这里是* viewController.m
#import "CoreDataEnsaViewController.h"
#import "CoreDataEnsaAppDelegate.h"
#import "ShowViewController.h"
#import "Contacts.h"
@implementation CoreDataEnsaViewController
ShowViewController *showView;
@synthesize name, address, phone, status, tableView;
@synthesize context = _context;
@synthesize fetchedResultsController = _fetchedResultsController;
-(IBAction) showbtn:(id) sender {
showView = [[ShowViewController alloc] initWithNibName:@"ShowViewController" bundle:nil];
//anima
[UIView beginAnimations:@"flipping view" context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown
forView:self.view cache:YES];
[self.view addSubview:showView.view];
[UIView commitAnimations];
}
- (void) saveData
{
CoreDataEnsaAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
newContact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:context];
[newContact setValue:name.text forKey:@"name"];
[newContact setValue:address.text forKey:@"address"];
[newContact setValue:phone.text forKey:@"phone"];
name.text = @"";
address.text = @"";
phone.text = @"";
NSError *error;
[context save:&error];
status.text = @"Contact saved";
}
- (void) findContact
{
CoreDataEnsaAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name = %@)", name.text];
[request setPredicate:pred];
NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
status.text = @"No matches";
} else {
matches = [objects objectAtIndex:0];
address.text = [matches valueForKey:@"address"];
phone.text = [matches valueForKey:@"phone"];
status.text = [NSString stringWithFormat:@"%d matches found", [objects count]];
}
[request release];
}
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contacts" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
//NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"details.closeDate" ascending:NO];
//[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_context sectionNameKeyPath:nil cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
[fetchRequest release];
[theFetchedResultsController release];
return _fetchedResultsController;
}
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
// Overriden to allow any orientation.
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
self.name = nil;
self.address = nil;
self.phone = nil;
self.status = nil;
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
//tabla
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
//return [array count];
//return [[fetchedResultsController sections] count];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
Contacts *info = [_fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = info.name;
cell.detailTextLabel.text = [NSString stringWithFormat:@"%@, %@", info.address, info.phone];
}
//---insert individual row into the table view---
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
//---try to get a reusable cell---
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//---create new cell if no reusable cell is available---
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
//tabla end
- (void)dealloc {
[name release];
[address release];
[phone release];
[status release];
self.fetchedResultsController = nil;
self.context = nil;
[super dealloc];
}
#pragma mark NSFetchedResultsControllerDelegate methods
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
// Reloading the section inserts a new row and ensures that titles are updated appropriately.
[tableView reloadSections:[NSIndexSet indexSetWithIndex:newIndexPath.section] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
[self.tableView endUpdates];}
@end
xib中的连接是&gt; 表视图 出口: 数据源-----------文件所有者; 委托--------------文件所有者; 引用网点 tableView -------------文件所有者; 非常感谢你!!!!
答案 0 :(得分:1)
对于“NSInternalConsistencyException”,请根据您的代码检查托管对象模型,并确保您正确地调用它。如果做不到这一点,你做了一个干净的,重新启动的XCode,重新启动你的计算机,从模拟器删除应用程序,通常的东西?如果您对文件进行了更改或将其换出,旧的东西有时会“潜伏”并导致这些问题。如果不这样做,有时当我遇到令人困惑的核心数据问题时,从头开始重建模型文件并自动创建子类就会解决它......不知道为什么。
我知道这不是你的问题,但是人们普遍不鼓励简单地为托管对象上下文调用app委托 - 尽管它确实有效并且你会在一些代码示例中看到它,但这不是最佳实践。它在您的项目中引入了不必要的依赖项,这将使您的代码难以维护。应用程序委托仅应用于处理系统级事件,而不是用于其他目的的“滥用”。更好的方法是为需要它的每个控制器创建一个托管对象上下文属性,并在创建该控制器时传递引用。您的App Delegate会将它传递给didFinishLaunchingWithOptions中的根视图控制器(只需设置接收控制器的属性),如下所示:
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions...
{
UINavigationController *navController = self.window.rootViewController
MyViewController *controller = navController.viewControllers[0];
controller.managedObjectContext = self.managedObjectContext;
return YES;
}
当根视图控制器需要将MOC传递给另一个控制器时,它会发生如下:
-(void)prepareForSegue...
{
MyOtherController *otherController = [segue destinationViewController];
controller.managedObjectContext = self.managedObjectContext;
}
等等,对于需要它的每个控制器。这样你就不会引入不必要的依赖关系,使你的代码更少模块化和可重用。
希望这会有所帮助。
答案 1 :(得分:0)
尝试添加此代码以在viewDidLoad方法中执行数据提取:
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(@"Unsolved error: %@, %@", error, [error userInfo]);
abort();
}