2011-09-08 4 views
0

속성 myAttribute가있는 클래스 (MyClass)가있는 경우 하위 클래스에서 사용할 수 없습니다. (mySubclass) self.myAttribute 호출하지 않고. 시뮬레이터로 앱을 실행할 때 이런 종류의 코드에는 문제가 없습니다. 당신은 궁금해 할 것입니다 : "왜 그녀는 이것을합니까?". 사방에 "자기"를 추가하는 것은 아주 쉽습니다. 문제는 MySubclass에서 MyClass의 접근 자 메서드를 재정의한다는 것입니다. 다음은 그 예입니다 :응용 프로그램이 장치에서 실행되지 않습니다. self.attribute를 사용하지 않고 하위 클래스에서 속성의 클래스를 호출 할 수 없습니다.

- (NSDateFormatter *)dateFormatter 
{ 
    if (dateFormatter == nil) 
    { 
     dateFormatter = [[NSDateFormatter alloc] init]; 
     // Do other stuff with the dateFormatter 
    } 

    return dateFormatter; 
} 

무한 루프가 발생하기 때문에 getter 내부에서 self.dateFormatter를 호출 할 수 없습니다. 나는 그 문제를 다루기 위해 수업을 리팩터링 할 수 있지만 그런 종류의 문제를 다루는 것은 좋은 해결책 일 수있다.

감사합니다.

+0

컴파일러 경고가 표시됩니까? 장치의 오류는 무엇입니까? 장치 용으로 컴파일됩니까? 또는 런타임에 오류가 있습니까? 컴파일이 전혀 안되면 (sim 및 device의 경우) private 속성과 관련된 문제가됩니다. 하지만 코드가 시뮬레이터에서 실행 중입니다. [super dateFormatter]를 시도하십시오. 그렇지 않으면 – thomas

+0

이 오류가 발생합니다 : dateFormatter 선언되지 않음 (이 함수의 첫 번째 사용) – strave

+0

근래에 로컬 변수를 만들었거나 속성으로 선언 한 적이 있습니까? – lukya

답변

1

self.property는 [self propertyGetter]와 매우 흡사합니다.

혼동을 피하기 위해 속성 이름과 인스턴스 변수가 같은 이름을 사용해서는 안됩니다.

가장 좋은 방법은 항상 ivars에 대한 공통 접두어를 미리 작성하는 것입니다. 구현

@implementation MyClass 
@synthetize dateFormatter= iVarDateFormatter; 
... 
@end 

에서

@interface MyClass { 
    // You don't have to declare iVar. Feel free to remove line. 
    NSDateFormatter * iVarDateFormatter; 
} 

@property (retain) NSDateFormatter * dateFormatter; 

@end 

그리고 그래서 당신은 쓸 수 있습니다 :

이 하나 싱글 개체에 대한
- (NSDateFormatter *) dateFormatter 
{ 
    if (nil == iVarDateFormatter) 
    { 
     iVarDateFormatter = [[NSDateFormatter alloc] init]; 
     // Do other stuff with the dateFormatter 
    } 

    return iVarDateFormatter; 
} 

더 좋은 GCD의 dispatch_once를 사용!

- (NSDateFormatter *) dateFormatter 
{ 
    static dispatch_once_t pred; 

    dispatch_once(& pred, ^{ 
     iVarDateFormatter = [[NSDateFormatter alloc] init]; 
     // Do other stuff with the dateFormatter 
    }); 

    return iVarDateFormatter; 
} 
+0

좋은 답변! 이것이 내가 질문을 게시 한 지 10 분 후 문제를 해결 한 방법입니다. 당신의 대답은 그 문제를 더욱 분명하게했습니다. 그리고 dispatch_once 팁 주셔서 감사합니다. 매우 유용합니다! – strave

관련 문제