2010-07-19 106 views
0

加載數據我已經爲我的應用程序正在開發的任何問題...
我使用的核心數據,我只是寫初始代碼...
但之一我的問題是:核心數據不會加載存儲在永久存儲數據...
這是我的代碼!

核心數據的應用程序不會從持久性存儲

MyWishesAppDelegate.h


MyWishesAppDelegate.m


#import "MyWishesAppDelegate.h" 


@implementation MyWishesAppDelegate 

@synthesize window; 
@synthesize tabBarController; 


#pragma mark - 
#pragma mark Application lifecycle 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  

    // Override point for customization after application launch. 
[window insertSubview:tabBarController.view atIndex:0]; 
    [window makeKeyAndVisible]; 

return YES; 
} 


- (void)applicationWillResignActive:(UIApplication *)application { 
    /* 
    Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions 
    (such as an incoming phone call or SMS message) 
    or when the user quits the application and it begins the transition to the background state. 
    Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
    */ 
} 


- (void)applicationDidEnterBackground:(UIApplication *)application { 
    /* 
    Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application 
    to its current state in case it is terminated later. 
    If your application supports background execution, called instead of applicationWillTerminate: when the user quits. 
    */ 
} 


- (void)applicationWillEnterForeground:(UIApplication *)application { 
    /* 
    Called as part of transition from the background to the inactive state: here you can undo many of the changes made on entering the background. 
    */ 
} 


- (void)applicationDidBecomeActive:(UIApplication *)application { 
    /* 
    Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, 
    optionally refresh the user interface. 
    */ 
} 


- (void)applicationWillTerminate:(UIApplication *)application { 

    NSError *error = nil; 
    if (managedObjectContext_ != nil) { 
     if ([managedObjectContext_ hasChanges] && ![managedObjectContext_ save:&error]) { 

      NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
      abort(); 
     } 
    } 
} 


#pragma mark - 
#pragma mark Core Data stack 


- (NSManagedObjectContext *)managedObjectContext { 

    if (managedObjectContext_ != nil) { 
     return managedObjectContext_; 
    } 

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 
    if (coordinator != nil) { 
     managedObjectContext_ = [[NSManagedObjectContext alloc] init]; 
     [managedObjectContext_ setPersistentStoreCoordinator:coordinator]; 
    } 
    return managedObjectContext_; 
} 


- (NSManagedObjectModel *)managedObjectModel { 

    if (managedObjectModel_ != nil) { 
     return managedObjectModel_; 
    } 
    NSString *modelPath = [[NSBundle mainBundle] pathForResource:@"MyWishes" ofType:@"momd"]; 
    NSURL *modelURL = [NSURL fileURLWithPath:modelPath]; 
    managedObjectModel_ = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 

    return managedObjectModel_; 
} 


- (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 

    if (persistentStoreCoordinator_ != nil) { 
     return persistentStoreCoordinator_; 
    } 

    NSURL *storeURL = [NSURL fileURLWithPath: [[self applicationDocumentsDirectory] stringByAppendingPathComponent: @"MyWishes.sqlite"]]; 

    NSError *error = nil; 
    persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) { 

     NSLog(@"Unresolved error %@, %@", error, [error userInfo]); 
     abort(); 
    }  

    return persistentStoreCoordinator_; 
} 


#pragma mark - 
#pragma mark Application's Documents directory 

- (NSString *)applicationDocumentsDirectory { 
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
} 


#pragma mark - 
#pragma mark Memory management 

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application { 
} 


- (void)dealloc { 

    [managedObjectContext_ release]; 
    [managedObjectModel_ release]; 
    [persistentStoreCoordinator_ release]; 

[tabBarController release]; 
    [window release]; 
    [super dealloc]; 
} 


@end 


WishlistViewController.h


#import UIKit/UIKit.h 
#import CoreData/CoreData.h 

@interface WishlistViewController : UITableViewController { 

@private 
NSFetchedResultsController *_fetchedResultsController; 

} 

@property (nonatomic, readonly) NSFetchedResultsController *fetchedResultsController; 

-(void)add; 
-(IBAction)edit; 

@end 


WishlistViewController.m


#import "WishlistViewController.h" 
#import "MyWishesAppDelegate.h" 

@implementation WishlistViewController 

@synthesize fetchedResultsController = _fetchedResultsController; 

#pragma mark - 
#pragma mark Actions 

-(void)add { 
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; 
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity]; 
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context]; 

NSError *error; 
if (![context save:&error]) 
    NSLog(@"Error saving entity: %@", [error localizedDescription]); 

// TODO: instantiate detail editing controller and push onto stack 
} 

-(IBAction)edit { 
BOOL editing = !self.tableView.editing; 
self.navigationItem.rightBarButtonItem.enabled = !editing; 
self.navigationItem.leftBarButtonItem.title = (editing) ? (@"Done") : (@"Edit"); 
[self.tableView setEditing:editing animated:YES]; 
} 

#pragma mark - 
#pragma mark View lifecycle 

-(void)viewDidLoad { 
[super viewDidLoad]; 
NSError *error = nil; 
if (![[self fetchedResultsController] performFetch:&error]) { 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Errore caricamento dati" 
       message:[NSString stringWithFormat:@"L'errore è stato: %@", [error localizedDescription]] 
       delegate:self 
      cancelButtonTitle:@"Ok!" 
      otherButtonTitles:nil]; 
    [alert show]; 
} 
} 

-(void)viewDidAppear:(BOOL)animated { 
UIBarButtonItem *editButton = self.editButtonItem; 
[editButton setTarget:self]; 
[editButton setAction:@selector(edit)]; 
self.navigationItem.leftBarButtonItem = editButton; 

UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd 
         target:self 
         action:@selector(add)]; 
self.navigationItem.rightBarButtonItem = addButton; 
[addButton release]; 
} 

#pragma mark - 
#pragma mark Memory management 

- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
} 

- (void)viewDidUnload { 
} 

- (void)dealloc { 
[_fetchedResultsController release]; 
    [super dealloc]; 
} 

#pragma mark - 
#pragma mark Table View Methods 

-(NSInteger)numberOfSectionsInTableView:(UITableView *)theTableView { 
NSUInteger count = [[self.fetchedResultsController sections] count]; 
if (count == 0) { 
    count = 1; 
} 
return count; 
} 

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
NSArray *sections = [self.fetchedResultsController sections]; 
NSUInteger count = 0; 
if ([sections count]) { 
    id sectionInfo = [sections objectAtIndex:section]; 
    count = [sectionInfo numberOfObjects]; 
} 
return count; 
} 

-(UITableViewCell *)tableView:(UITableView *)theTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *WishlistTableViewCell = @"WishlistTableViewCell"; 

UITableViewCell *cell = [theTableView dequeueReusableCellWithIdentifier:WishlistTableViewCell]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:WishlistTableViewCell] autorelease]; 
} 

NSManagedObject *oneWish = [self.fetchedResultsController objectAtIndexPath:indexPath]; 
cell.textLabel.text = [oneWish valueForKey:@"nome"]; 

/*UIImageView *cellBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cellBg.png"]]; 
cell.backgroundView = cellBg;*/ 
/*cell.detailTextLabel.text = [oneWish valueForKey:@"costo"];*/ 

return cell; 
} 

-(void)tableView:(UITableView *)theTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
// TODO: instantiate detail editing view controller and push onto stack 
} 

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { 

if (editingStyle == UITableViewCellEditingStyleDelete) { 
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext]; 
    [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]; 

    NSError *error; 
    if (![context save:&error]) { 
    NSLog(@"Errore non risolto: %@, %@", error, [error userInfo]); 
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Errore salvataggio dati" 
       message:@"Impossibile salvare dopo aver cancellato un elemento" 
       delegate:self 
       cancelButtonTitle:@"Ok!" 
       otherButtonTitles:nil]; 
    [alert show]; 
    } 
} 
} 

#pragma mark - 
#pragma mark Fetched Results Controller 

-(NSFetchedResultsController *)fetchedResultsController { 

if (_fetchedResultsController != nil) { 
    return _fetchedResultsController; 
} 

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
MyWishesAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext; 

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Wish" inManagedObjectContext:managedObjectContext]; 

NSString *sectionKey = nil; 
NSSortDescriptor *sortByName = [[NSSortDescriptor alloc] initWithKey:@"nome" ascending:YES]; 
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortByName, nil]; 
[fetchRequest setSortDescriptors:sortDescriptors]; 
[sortByName release]; 
[sortDescriptors release]; 
sectionKey = @"nome"; 

[fetchRequest setEntity:entity]; 
[fetchRequest setFetchBatchSize:20]; 

NSFetchedResultsController *frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest 
        managedObjectContext:managedObjectContext 
        sectionNameKeyPath:sectionKey 
         cacheName:@"Wish"]; 
frc.delegate = self; 
_fetchedResultsController = frc; 
[fetchRequest release]; 

return _fetchedResultsController; 
} 

-(void)controllerWillChangeContent:(NSFetchedResultsController *)controller { 
[self.tableView beginUpdates]; 
} 

-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller { 
[self.tableView endUpdates]; 
} 

-(void)controller:(NSFetchedResultsController *)controller 
    didChangeObject:(id)anObject 
    atIndexPath:(NSIndexPath *)indexPath 
forChangeType:(NSFetchedResultsChangeType)type 
    newIndexPath:(NSIndexPath *)newIndexPath { 

switch(type) { 
    case NSFetchedResultsChangeInsert: 
    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    break; 
    case NSFetchedResultsChangeDelete: 
    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 
    break; 
    case NSFetchedResultsChangeUpdate: { 
    NSString *sectionKeyPath = [controller sectionNameKeyPath]; 
    if (sectionKeyPath == nil) 
    break; 
    NSManagedObject *changedObject = [controller objectAtIndexPath:indexPath]; 
    NSArray *keyParts = [sectionKeyPath componentsSeparatedByString:@"."]; 
    id currentKeyValue = [changedObject valueForKeyPath:sectionKeyPath]; 
    for (int i = 0; i)sectionInfo 
    atIndex:(NSUInteger)sectionIndex 
forChangeType:(NSFetchedResultsChangeType)type { 

switch(type) { 
    case NSFetchedResultsChangeInsert: 
    if (!(sectionIndex == 0 && [self.tableView numberOfSections] == 1) && [self.tableView numberOfRowsInSection:0] == 0) 
    [self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
    break; 
    case NSFetchedResultsChangeDelete: 
    if (!(sectionIndex == 0 && [self.tableView numberOfSections] == 1) && [self.tableView numberOfRowsInSection:0] == 0) 
    [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade]; 
    break; 
    case NSFetchedResultsChangeMove: 
    break; 
    case NSFetchedResultsChangeUpdate: 
    break; 
    default: 
    break; 
} 
} 

#pragma mark - 
#pragma mark Alert View Delegate 

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { 
exit(-1); 
} 


@end 

任何人都可以幫我嗎?如果在此代碼中的其他問題,可以這麼說我......

+1

您需要更好地描述實際問題。 「核心數據不會加載存儲在持久性存儲中的數據」並沒有給我們太多的提示。你有什麼錯誤嗎?你在桌上看到什麼?您能否無誤地將數據寫入商店?依此類推...... – TechZen 2010-07-19 17:21:16

+1

什麼不正確? (你收到了哪個錯誤信息?) - 或者 - 你預期會發生什麼?反而發生了什麼? – 2010-07-19 17:21:39

+0

不幸的是我沒有得到錯誤...不過我啓動我的應用程序在模擬器和我精讀點擊添加按鈕在...的行添加表中添加一行,但如果我完全關閉我的應用程序,如果我重新啓動它,我什麼也看不到表視圖... – matteodv 2010-07-19 17:34:45

回答

0

開始通過在調試器與objc_exception_throw斷點,這將導致您的應用程序停止崩潰,所以你可以看到問題的代碼行就是剛之前運行。這會告訴你是什麼導致了這個問題。

0

檢查我相信

#pragma mark Application's Documents directory 

- (NSString *)applicationDocumentsDirectory { 
    return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; 
} 

返回的值,這應該是:

- (NSString *)applicationDocumentsDirectory { 
    return [(NSArray *)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
} 
+0

'-lastObject'只會導致零回來,其中*應*給他推出一個錯誤。 – 2010-07-23 17:59:05

相關問題