我基本上想给一个类的每个实例一个唯一的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];
}
}
答案 0 :(得分:2)
我不确定为什么编译器没有抱怨,但问题的一部分在这里:
thisPageNumber = pageCount;
NSNumber
是一个对象。要将其设置为当前pageCount
值,请使用
thisPageNumber = [[NSNumber alloc] initWithInt:pageCount];
答案 1 :(得分:0)
为什么不直接使用self
作为唯一ID?它是独一无二的。