简体   繁体   中英

Why am I getting a different instance of a ViewController than the one I pushed onto the navigationController?

Why would I be getting a different instance of HistoryViewController than the one I instantiated and pushed onto the navigationController?

The different instance created doesn't have any of the properties I've set.

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();
    }
}

The instance is the same, the references to the same instance are different (which is fine).

The method viewDidLoad is called before you set the variables which is why self.managedObjectContext == nil.

Either write a custom init method which take parameters history and managedobjectcontext and set them in the init. Or instead of using viewDidLoad, use viewWillAppear:animated...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM