我基本上想给类的每个实例一个唯一的ID。
所以,我创建了一个静态整数。每次创建一个新对象时,我都会增加它,然后将静态变量的值赋给一个ivar。但是很明显我不理解,因为,假设我创建了三个对象,“thispagenumber”(它是实例变量)总是3,不管我引用哪个对象。
更多信息:
此类创建许多“页面”对象。我想让每一页都知道它的页码,这样它就可以显示正确的页面艺术以及执行许多其他各种操作。
.h部分代码:
@interface Page : UIViewController
{
NSNumber *thisPageNumber;
UIImageView *thisPageView;
UIImageView *nextPageView;
UIImageView *prevPageView;
UIImageView *pageArt;
}
.m部分代码:
@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:@"Page%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];
}
}