In my app, I made a BookViewController class that displays and animates the pages of a book and a MainMenuViewController class that displays a set of books the user can read.
In the latter class, when the user taps on one of the books, a function is called that should create a completely new instance of BookViewController, but for some reason the instance maintains its state (i.e. it resumes from the page the user left off).
How can this be if I set it to nil? What am I missing here? (Note that I’m using ARC).
MainMenuViewController.m
@interface MainMenuViewController ()
@property (strong) BookViewController *bookViewController;
@end
@implementation MainMenuViewController
@synthesize bookViewController;
-(void)bookTapped:(UIButton *)sender{
NSString *bookTitle;
if(sender == book1button) bookTitle = @"book1";
else if(sender == book2button) bookTitle = @"book2";
bookViewController = nil;
bookViewController = [[BookViewController alloc] initWithBookTitle:bookTitle];
[self presentViewController:bookViewController animated:YES completion:nil];
}
BookViewController.h
@interface BookViewController : UIViewController
-(id)initWithBookTitle:(NSString *)bookTitle;
@end
BookViewController.m
@implementation BookViewController
-(id)initWithBookTitle:(NSString *)theBookTitle{
self = [super init];
if(self){
bookTitle = [NSString stringWithFormat:@"%@", theBookTitle];
[self setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
NSLog(@"init a BookViewController with bookTitle: %@", bookTitle);
}
return self;
}
edit 1:
Every time a book is tapped, bookTapped: is called, and thee console always prints:
2012-08-31 16:29:51.750 AppName[25713:c07] init a BookViewController with bookTitle: book1
So if a new instance of BookViewController is being created, how come it seems to be returning the old one?
edit 2:
I inserted NSLog(@"bookViewController %@",bookViewController); just before the line [self presentViewController:bookViewController. The console output is:
2012-08-31 16:37:41.426 Henry[25784:c07] bookViewController <BookViewController: 0x6a21540>
2012-08-31 16:38:23.321 Henry[25784:c07] bookViewController <BookViewController: 0xe425540>
2012-08-31 16:38:53.393 Henry[25784:c07] bookViewController <BookViewController: 0x6839330>
Your variables are declared outside of the @implementation of the class (you are declaring global variables).