我有一些ViewControllers。在我登录的第一个LoginViewController中,我创建了newEntity。通过单击“登录”按钮,我通过谓词“login”进行获取并为此newEntity提取分配。 AppDelegate.h为Core Data创建了一些东西。在LoginViewController中,我在.h中有下一个字符串:
@class AppDelegate;
...
@property (strong, nonatomic) AppDelegate *appMeDelegate;
@property (strong, nonatomic) NSManagedObjectContext *context;
...
在LoginViewController.m中
#import "AppDelegate.h"
...
@synthesize ... appMeDelegate, context;
...
//I have login button where i compare login and password in
//UITextFields with that in Core Data and if it is
//all right i load fetch for user with his login
-(IBAction)login:
{
appMeDelegate = (AppDelegate *) [[UIApplication sharedApplication]delegate];
context = appMeDelegate.managedObjectContext;
NSFetchRequest * fetchRequest = [[NSFetchRequest alloc]init];
NSPredicate *predicateMe = [NSPredicate predicateWithFormat:@"login==%@",login.text];
fetchRequest.predicate = predicateMe;
... //then I create newEntity }
//next method for saving
-(void)saving
{
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}}
然后在其他ViewController中我使用newEntity但无法保存它
- (void)viewDidLoad
{
[super viewDidLoad];
NSData *newdata = [NSData dataWithData:self.loginViewController.newEntity.photo];
photoArray = [NSMutableArray arrayWithArray:
[NSKeyedUnarchiver unarchiveObjectWithData:newdata]];}
-(IBAction)save
{ [photoArray addObject:myImage];
NSData *newData = [NSKeyedArchiver archivedDataWithRootObject:photoArray];
[self.loginViewController.newEntity setValue:newData forKey:@"photo"];
[self.loginViewController saving];
但没有结果,也没有保存实体的变化
答案 0 :(得分:1)
您可以使用类似的方法来保存您的managedDocument上下文
[self.managedDocument saveToURL: self.managedDocument.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:^(BOOL success) {
if (completionHandler) completionHandler(success);
}];
修改强> 对不起,刚看到您显然没有使用NSManagedDocument(您应该查看)。
不要这样做:
[self.loginViewController saving];
像以前那样做:
appMeDelegate = (AppDelegate *) [[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = appMeDelegate.managedObjectContext;
[context save: &error];