2010-07-12 6 views
1

기본적으로 클래스의 각 인스턴스에 고유 한 ID를 부여하려고합니다.Objective-C : 정적 변수의 값을 인스턴스 변수에 할당

그래서 정적 정수를 만들었습니다. 나는 새로운 객체가 생성 될 때마다 그것을 증가시킨 다음 정적 변수의 값을 ivar에 할당합니다. 하지만 분명히 나는 ​​어떤 것을 이해하지 못한다. 내가 세 개의 객체를 생성한다고 가정 해 보자. 인스턴스 변수 인 thisPageNumber는 내가 참조하는 객체에 상관없이 항상 3이다.

자세한 정보 :

이 클래스는 여러 "페이지"개체를 만듭니다. 각 페이지가 올바른 페이지 아트를 표시 할 수있을뿐만 아니라 다양한 다양한 작업을 수행 할 수 있도록 페이지 번호를 알고 싶습니다.

.H 부분 코드 :

@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

확인 하시겠습니까? 현재 접속하고있는 코드를 표시 할 수 있습니까? –

+0

또한 클래스의 인터페이스 – JeremyP

+0

몇 가지 추가 소스 코드를 추가했습니다. – RyJ

답변

2

나는 컴파일러가 불평하지 않았는지 모르겠지만, 문제의 부분은 여기에 있습니다 :

thisPageNumber = pageCount; 

NSNumber 개체입니다. 현재 pageCount 값으로 설정하려면

thisPageNumber = [[NSNumber alloc] initWithInt:pageCount]; 
+0

OMG, 이런! 고마워, 그거야. "thisPageNumber"는 처음에이 주제를 게시했을 때 실제로 int였습니다. 그런 다음에 코드를 추가하여 내 작업과 함께 NSNumber로 변경했습니다. 비용을 불문하고 모든 것이 이제는 훌륭하게 작동하는 것 같습니다. 고마워요! – RyJ

0

왜 그냥 고유 ID로 self을 사용하지 마십시오

@interface Page : UIViewController 
{ 
    NSNumber   *thisPageNumber; 
    UIImageView   *thisPageView; 
    UIImageView   *nextPageView; 
    UIImageView   *prevPageView; 
    UIImageView   *pageArt; 
} 

이 부분 코드를하는 .m? 그것은 독특합니다.

+0

프로그램에서 주어진 시간에 고유합니다. self의 값은 객체가 dealloc 된 후에 재사용 될 수 있습니다. 이것은 특정 유일성 요구 사항에 문제가 될 수 있습니다. –

+0

또한 id로부터 생성 순서를 아는 것은 예를 들어. 로그를 평가할 때 도움이됩니다. –

+0

아, 그 말이 맞습니다. 우리는 RyJ가 필요로하는 독창성의 종류를 알아야합니다. – Yuji

관련 문제