簡體   English   中英

核心數據問題。 數據無法保存

[英]Core Data issue. Data won't save

因此,我有一個實用應用程序,我試圖將一些文本保存到Flipside View Controller上的“ To”和“ Message:”文本字段中。但是,我的數據無法保存。我對目標C還是陌生的使用了多個不同的教程,使我完全感到困惑。希望您能為我提供幫助。不確定目前還需要做什么...

FlipsideViewController.m

#import "CCCFlipsideViewController.h"
#import "CCCAppDelegate.h"
#import "CCCMainViewController.h"
#import "MessageDetails.h"

@interface CCCFlipsideViewController ()
{
   // NSManagedObjectContext *context;
}
@end

@implementation CCCFlipsideViewController
@synthesize allMessageDetails;
@synthesize managedObjectContext;

- (void)awakeFromNib
{
    [super awakeFromNib];

    CCCAppDelegate *appDelegateController = [[CCCAppDelegate alloc]init];
    self.managedObjectContext = appDelegateController.managedObjectContext;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"MessageDetails" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    NSError *error;

    self.allMessageDetails = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];

    /*
    NSManagedObject *managedObject; = [_fetchedResultsController valueForKey:@"to"];
    self.toTextField.text = managedObject to;

    messageDetails.to = [allMessageDetails firstObject];
    self.toTextField.text = messageDetails.to;

    messageDetails.message = [allMessageDetails valueForKey:@"message"];
    self.messageTextField.text = messageDetails.message;
    */
    NSLog(@"The 'to' is currently at %@ after viewdidload", self.toTextField.text);

    }

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
   return [textField resignFirstResponder]; //function says that if (bool) the text field is open and the keyboard hits return, text field is to resign first responder.
}

#pragma mark - Actions
- (IBAction)done:(id)sender
{
    [self.delegate flipsideViewControllerDidFinish:self];
}

- (IBAction)resignFirstResponder:(id)sender {

    [self.toTextField resignFirstResponder];
    [self.messageTextField resignFirstResponder];
    NSLog(@"Resigned First Responder");
}


- (IBAction)save:(id)sender {

    // Create a new instance of the entity managed by the fetched results controller.
   NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
    NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];

    // If appropriate, configure the new managed object.
    [newManagedObject setValue:self.toTextField.text forKey:@"to"];
    [newManagedObject setValue:self.messageTextField.text forKey:@"message"];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }


}


#pragma mark -
#pragma mark Fetched results controller

- (NSFetchedResultsController *)fetchedResultsController {

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

    /*
     Set up the fetched results controller.
     */
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MessageDetails" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"to" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Edit the section name key path and cache name if appropriate.
    // nil for section name key path means "no sections".
    NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:@"Root"];
    aFetchedResultsController.delegate = self;
    self.fetchedResultsController = aFetchedResultsController;


    NSError *error = nil;
    if (![_fetchedResultsController performFetch:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

    return _fetchedResultsController;
}


@end

我沒有查看您的所有代碼,因為頂部附近存在一個問題,該問題否定了您以后所做的一切。 不要在aakeakeFromNib或其他任何地方分配/初始化您的應用程序委托。 您的應用程序委托的唯一實例已經存在(我不知道當有多個應用程序委托時會發生什么)。

CCCFlipsideViewController需要通過另一種方式來訪問托管對象上下文。 也許CCCMainViewController(或另一個視圖控制器)可以設置CCCFlipsideViewController的managedObjectContext屬性。 如果CCCMainViewController無權訪問托管對象上下文,則讓應用程序委托將該上下文傳遞給它。

示例:應用程序委托在根視圖控制器上設置了ManagedObjectContext屬性; 根視圖控制器依次在子視圖控制器(如您的反面VC)上設置managedObjectContext屬性,等等。

您似乎從未真正將self.messageTextField.text或self.toTextField.text設置為任何值-您已在設置這些字段的viewDidLoad方法中注釋掉了代碼。 關於您的AppDelegate問題,bilobatum也完全正確-您也可以使用類似

[((NSObject*)[UIApplication sharedApplication].delegate) valueForKey: @"managedObjectContext"];

如果您想快速解決問題,可以為您的應用程序獲取應用程序委托,盡管長期的loblobatum解決方案是更好的設計。

老實說,我認為您已經在此代碼上做了很多工作...;)

好吧,首先,在您的save方法中,不要創建另一個NSManagedObjectContext,使用已經聲明的實例變量“ managedObjectContext”。

其次,我認為您使事情變得太復雜了……創建NSManagedObject子類並在App Delegate中設置所有內容后,存儲核心數據實際上非常簡單。

似乎您的代碼此時不需要“ fetchedResultsController”中的任何信息,因為這是保存而不是獲取。 也許嘗試將您的保存方法更改為:

- (IBAction)save:(id)sender {

    NSEntityDescription *entity = [NSEntityDescription insertNewObjectForEntityForName:@"MessageDetails" inManagedObjectContext:self.managedObjectContext];

    // If appropriate, configure the new managed object.
    [entity setValue:self.toTextField.text forKey:@"to"];
    [entity setValue:self.messageTextField.text forKey:@"message"];

    // Save the context.
    NSError *error = nil;
    [self.managedObjectContext save:&error]

    if (error) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
     */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }

}


編輯:並從應用程序委托獲取托管對象的上下文...

在@synthesize之后,立即為App Delegate創建一個變量。

AppDelegate* appDelegateController;

然后在viewDidLoad中將其初始化:

appDelegateController = (AppDelegate*)[[UIApplication sharedApplication] delegate];

在viewDidLoad之后(或您想要的任何地方)之后,可以使用一種方法聲明托管對象的上下文:

- (NSManagedObjectContext*)managedObjectContext {
    return appDelegateController.managedObjectContext;
}

然后回到viewDidLoad中,使用以下方法調用該方法:

self.managedObjectContext = [self managedObjectContext];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM