核心数据保存错误

时间:2011-02-13 18:39:38

标签: iphone objective-c cocoa-touch core-data ios4

我正在尝试将一些数据从不同的视图保存到核心数据,当我按下按钮保存数据时,我不断收到错误。我得到的是:

Unresolved error (null), (null)

这是我的所有代码:

SomeViewController.h

#import <UIKit/UIKit.h>
@class NameData;
@interface SomeViewController : UIViewController <NSFetchedResultsControllerDelegate> {
    NSFetchedResultsController *fetchedResultsController;
    NSManagedObjectContext* managedObjectContext;
    NameData *nameData;
}
@property (nonatomic,retain) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic,retain) NSManagedObjectContext* managedObjectContext;
@property (nonatomic,retain) NameData *nameData;

- (IBAction)saveData;

@end

SomeViewController.m

#import "SomeViewController.h"
#import  "NameData"

@implementation SomeViewController

@synthesize addTeam;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Add Name;

}

- (IBAction)saveData{

    NSString *string = @"demo";

    nameData.nameContent = string;
    nameData.name2Content = string;
    nameData.name3Content = string;


    NSError *error = nil;
    if (![nameData.managedObjectContext save:&error]) {
        // Handle error
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();  // Fail
    }   
}
- (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 {
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [nameData release];
}
@end

NameData.h

#import <CoreData/CoreData.h>


@interface NameData :  NSManagedObject  
{
}

@property (nonatomic, retain) NSString * nameContent;
@property (nonatomic, retain) NSString * name2Content;
@property (nonatomic, retain) NSString * name3Content;
@end

NameData.m

#import "NameData"

@implementation NameData

@dynamic nameContent;
@dynamic name2Content;
@dynamic name3Content;
@end

1 个答案:

答案 0 :(得分:2)

save应该在managedObjectContext实例上执行,而不是模型本身。

示例:

NSError *error;
NSManagedObjectContext *moc = [self.fetchedResultsController managedObjectContext];
if (![moc save:&error]) {
    NSLog(@"Failed to save to data store: %@ - %@", 
          [error localizedDescription], [error userInfo]);
}