代码之家  ›  专栏  ›  技术社区  ›  RyJ

目标C:将静态变量的值赋给实例变量

  •  1
  • RyJ  · 技术社区  · 14 年前

    我基本上想给类的每个实例一个唯一的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];
        }    
    }
    
    2 回复  |  直到 14 年前
        1
  •  2
  •   kubi    14 年前

    我不知道编译器为什么没有抱怨,但您的部分问题在于:

    thisPageNumber = pageCount;
    

    NSNumber 是一个对象。将其设置为当前 pageCount 使用价值

    thisPageNumber = [[NSNumber alloc] initWithInt:pageCount];
    
        2
  •  0
  •   Yuji    14 年前

    你为什么不直接用 self 作为唯一ID?这是独一无二的。