2011-02-13 147 views
0

我試圖從不同的視圖保存一些數據,核心數據和我不斷收到一個錯誤,當我按下按鈕來保存數據。在我得到的是:核心數據保存錯誤

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 
+0

這將是有益的顯示錯誤是什麼。 – chris 2011-02-13 18:43:08

+0

確實。把你的NSLog更改爲:NSLog(@「未解析的錯誤%@,%@」,錯誤,[錯誤localizedDescription]);`。 – lxt 2011-02-13 18:47:19

回答

2

保存應在managedObjectContext情況下進行,而不是模型本身。

例子:

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