为什么我得到一个ViewController的不同实例而不是我推送到navigationController的实例?

时间:2010-07-02 17:53:14

标签: iphone objective-c uiviewcontroller uinavigationcontroller nsmanagedobjectcontext

为什么我会获得一个不同于HistoryViewController的实例而不是我实例化并推送到navigationController的实例?

创建的不同实例没有我设置的任何属性。

ProfileHomeViewController.m

HistoryViewController *historyViewController = nil;
historyViewController = [[HistoryViewController alloc] initWithNibName:@"HistoryViewController" bundle:nil];
// nib has identity of NSObject (I also tried HistoryViewController), and tableviewcontroller with identity HistoryViewController
historyViewController.profile = self.profile;

NSLog(@"%@ > %@", self, self.managedObjectContext);
// <ProfileHomeViewController: 0x5b34330> > <NSManagedObjectContext: 0x7918770>


historyViewController.managedObjectContext = self.managedObjectContext;
NSLog(@"%@ > %@", historyViewController, historyViewController.managedObjectContext);
// <HistoryViewController: 0x792a870> > <NSManagedObjectContext: 0x7918770>

[self.navigationController pushViewController:historyViewController animated:YES];
[historyViewController release];

HistoryViewController.h

@interface HistoryViewController : UITableViewController {

    NSManagedObject *profile;
    NSFetchedResultsController *fetchedResultsController;
    NSManagedObjectContext *managedObjectContext;

}

@property (nonatomic, retain) NSManagedObject *profile;
@property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

HistoryViewController.m

@implementation HistoryViewController

@synthesize profile;
@synthesize fetchedResultsController;
@synthesize managedObjectContext;


- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"inside HistoryViewController %@ > profile %@", self, self.profile);
    // inside HistoryViewController <HistoryViewController: 0x7917750> > profile (null)

    NSLog(@"inside HistoryViewController %@ > managedObjectContext %@", self, self.managedObjectContext);
    // inside HistoryViewController <HistoryViewController: 0x7917750> > managedObjectContext (null)

    if(self.managedObjectContext == nil){
            NSLog(@"invalid managedObjectContext WTF");
            abort();
    }
}

1 个答案:

答案 0 :(得分:0)

实例是相同的,对同一实例的引用是不同的(这很好)。

方法viewDidLoad在 之前被称为 ,你设置变量就是self.managedObjectContext == nil。

编写一个自定义init方法,该方法接受参数history和managedobjectcontext并在init中设置它们。或者不使用viewDidLoad,而是使用viewWillAppear:animated ...