Objective-C: Assigning the value of a static variable to an instance variable
I essentially want to give each instance of a class a unique id.
So, I created a static integer. I increment it each time a new object is created and then assign the value of the static variable to an ivar. But clearly I don't understand something because, let's say I create three objects, "thisPageNumber" (which is the instance variable) is always 3 no matter which object I reference.
More information:
This class creates a number of "Page" objects. I'd like each page to know it's page number so that it can display the correct page art as well as perform a number of other various actions.
.h partial code:
@interface Page : UIViewController
{
NSNumber *thisPageNumber;
UIImageView *thisPageView;
UIImageView *nextPageView;
UIImageView *prevPageView;
UIImageView *pageArt;
}
.m partial code:
@implementation Page
static int pageCount = 0;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
pageCount++;
thisPageNumber = pageCount;
}
return self;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
CGRect defaultFrame = CGRectMake(0.0, 0.0, 1024.0, 768.0);
if (thisPageView == nil) {
thisPageView = [[UIImageView alloc]
initWithImage:[UIImage
imageNamed:[NSString stringWithFormat:@"Pag开发者_开发知识库e%i.png", [thisPageNumber intValue]]]];
thisPageView.frame = defaultFrame;
[self.view addSubview:thisPageView];
}
if (nextPageView == nil && [thisPageNumber intValue] < BOOK_PAGE_COUNT) {
nextPageView = [[UIImageView alloc]
initWithImage:[UIImage
imageNamed:[NSString stringWithFormat:@"Page%i.png", [thisPageNumber intValue]+1]]];
nextPageView.frame = defaultFrame;
[self.view addSubview:nextPageView];
}
if (prevPageView == nil && [thisPageNumber intValue] > 1) {
prevPageView = [[UIImageView alloc]
initWithImage:[UIImage
imageNamed:[NSString stringWithFormat:@"Page%i.png", [thisPageNumber intValue]-1]]];
prevPageView.frame = defaultFrame;
[self.view addSubview:prevPageView];
}
}
I'm not sure why the compiler didn't complain, but part of your problem is here:
thisPageNumber = pageCount;
NSNumber
is an object. To set it to the current pageCount
value, use
thisPageNumber = [[NSNumber alloc] initWithInt:pageCount];
Why don't you just use self
as the unique ID? It's unique.
精彩评论