我正在尝试将一些NSStrings保存到Core Data,然后从另一个视图控制器中的UITableView访问它们。这是我用来将字符串保存到Core Data的代码:
- (IBAction)GoBackButton:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new managed object
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
[newDevice setValue:Title forKey:@"title"];
[newDevice setValue:Step1 forKey:@"step1"];
[newDevice setValue:Step2 forKey:@"step2"];
[newDevice setValue:Step3 forKey:@"step3"];
[newDevice setValue:img forKey:@"imagename"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
[self performSegueWithIdentifier: @"goBack" sender: self];
reloadType = @"YES";
//[self dismissViewControllerAnimated:YES completion:nil];
}
这是我用来尝试通过segue传回数据的方法:
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if([segue.identifier isEqualToString:@"goBack"]){
[[segue destinationViewController]setManagedObjectContext:self.device];
}
}
但是,行:
[[segue destinationViewController]setManagedObjectContext:self.device];
带来错误“没有已知的选择器实例方法'setManagedObjectContext:'。如果需要,我可以发布更多我的核心数据模型创建代码,以帮助找到解决此问题的方法。
答案 0 :(得分:2)
除非你的其他viewcontroller也应该有权访问核心数据方法(比如能够读写你的数据库)。我强烈建议您将字符串添加到数组或字典中,然后传递它。
无论如何,它不起作用的原因是因为你必须导入你的其他视图控制器头,然后再投射它。
类似的东西:
MyOtherVC *temp = [segue destinationViewController];
[temp theMethodIWannaUse:theData];
此外,您必须在其他视图控制器上实现它,就像您要设置核心数据一样,您必须在标头(或至少是您要使用的方法)中公开您的核心数据对象您的目标视图控制器。
编辑:
要呈现的VC必须在标题中包含此内容:
@property (weak,nonatomic) NSManagedObjectContext *context;
然后在准备segue时将其传递给这样:
MyOtherVC *temp = [segue destinationViewController];
[temp theMethodIWannaUse:theData];
temp.context = *theContext*;
答案 1 :(得分:0)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
DetailComplaints *detailComplaints = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]
instantiateViewControllerWithIdentifier:@"DetailComplaints"];
detailComplaints.tempWebData=[self.detailWebServce objectAtIndex:indexPath.row];
//detailComplaints.tempName=[self.detailWebServce valueForKey:@"username"];
[self.navigationController pushViewController:detailComplaints animated:YES];
}
并收到像这样的其他视图控制器...
`
-(NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
// NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
` 然后..
_txt_name.text= [self.tempWebData valueForKey:@"username"];
_txt_address.text=[self.tempWebData valueForKey:@"address"];
_txt_phone.text=[self.tempWebData valueForKey:@"phonenumber"];