NSManagedObject的值突然变为null

时间:2014-04-12 20:27:20

标签: ios objective-c core-data nsmanagedobject

我的申请存在问题。在viewDidLoad方法中,_recipe对象将打印出其值。但是,当调用addToFavourites方法时,_recipe对象的值将返回null,而我无法理解为什么会有任何帮助受到重视。

继承课程。

  #import "DetailViewController.h"
  #import "Recipe.h"
  #import "AppDelegate.h"

  @interface DetailViewController ()

  @end

  @implementation DetailViewController

  - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
 {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    // Custom initialization
 }
   return self;
 }

 - (void)viewDidLoad
{
 [super viewDidLoad];
// Do any additional setup after loading the view.

   self.recipetitle.text = _recipe.title;

   self.recipeingrediants.text = _recipe.ingrediants;
   self.recipemethod.text = _recipe.method;

  NSString *str = self.recipe.img64;
 NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:0];

self.recipeimage.image = [UIImage imageWithData:data];
   NSLog(@"This is odd.. %@",_recipe.title);
 }

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

 - (IBAction)addToFavourites:(id)sender {

NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication]     delegate] managedObjectContext];
Recipe *favourite = [NSEntityDescription insertNewObjectForEntityForName:@"Recipe" inManagedObjectContext:context];


[favourite setValue:self.recipe.title forKey:@"title"];
 [favourite setValue:_recipe.ingrediants forKey:@"ingrediants"];

NSLog(@"ERMM WHAT %@",_recipe.title);
 [favourite setValue:_recipe.method forKey:@"method"];
 [favourite setValue:_recipe.img64 forKey:@"img64"];
 [favourite setValue:_recipe.type forKey:@"type"];


NSError *err;
[context save:&err];

NSLog(@"SAVE FIRED");

}
@end

1 个答案:

答案 0 :(得分:0)

好的,我已经弄明白了!对_recipe的引用是weak!因此,当viewDidLoad方法结束时,前一个视图被放在堆上。由于_recipe没有额外的引用计数,它也在堆上!