program story

Objective-C와 동등한 정적 생성자?

inputbox 2020. 10. 31. 09:40
반응형

Objective-C와 동등한 정적 생성자?


저는 Objective C를 처음 접했고 언어에 정적 생성자와 동등한 것이 있는지 확인할 수 없었습니다. 즉, 해당 클래스의 첫 번째 인스턴스 전에 자동으로 호출되는 클래스의 정적 메서드입니다. 인스턴스화됩니다. 아니면 초기화 코드를 직접 호출해야합니까?

감사


+initialize메서드는 클래스 메서드가 사용되거나 인스턴스가 생성되기 전에 클래스가 처음 사용될 때 자동으로 호출 됩니다 . +initialize자신에게 전화해서는 안됩니다 .

나는 또한 길을 밟을 수 있다는 것을 배웠습니다. +initialize하위 클래스에 의해 상속되며 +initialize자체를 구현하지 않는 각 하위 클래스에 대해 호출됩니다 . .NET에서 싱글 톤 초기화를 순진하게 구현하는 경우 특히 문제가 될 수 있습니다 +initialize. 해결책은 다음과 같이 클래스 변수의 유형을 확인하는 것입니다.

+ (void) initialize {
  if (self == [MyParentClass class]) {
    // Once-only initializion
  }
  // Initialization for this class and any subclasses
}

NSObject의에서 내려 모든 클래스는 모두가 +class-class반환 방법 Class개체를. 각 클래스에 대해 하나의 Class 객체 만 있기 때문에 ==연산자 와의 동등성을 테스트하고 싶습니다 . 이를 사용하여 주어진 클래스 아래의 계층 구조 (아직 존재하지 않을 수도 있음)의 각 개별 클래스에 대해 한 번이 아니라 한 번만 발생해야하는 작업을 필터링 할 수 있습니다.

접선 주제에 대해 아직 배우지 않았다면 다음과 같은 관련 방법에 대해 알아볼 가치가 있습니다.


편집 : 자세한 내용을 설명 하는 @bbum 의이 게시물을 확인하십시오 +initialize. http://www.friday.com/bbum/2009/09/06/iniailize-can-be-executed-multiple-times-load-not-so- 많은/

또한 Mike Ash는 +initialize+load메서드 에 대한 자세한 금요일 Q & A를 작성했습니다 . https://www.mikeash.com/pyblog/friday-qa-2009-05-22-objective-c-class-loading-and-initialization.html


클래스가 사용되기 전에 호출 되는 + initialize 클래스 메서드가 있습니다.


이 주제에 대한 약간의 부록 :

__attribute지시문을 사용하여 obj-c에서 '정적 생성자'를 만드는 또 다른 방법이 있습니다 .

// prototype
void myStaticInitMethod(void);

__attribute__((constructor))
void myStaticInitMethod()
{
    // code here will be called as soon as the binary is loaded into memory
    // before any other code has a chance to call +initialize.
    // useful for a situation where you have a struct that must be 
    // initialized before any calls are made to the class, 
    // as they would be used as parameters to the constructors.
    // e.g.
    myStructDef.myVariable1 = "some C string";
    myStructDef.myFlag1 = TRUE; 

    // so when the user calls the code [MyClass createClassFromStruct:myStructDef], 
    // myStructDef is not junk values.
}

참고 URL : https://stackoverflow.com/questions/992070/static-constructor-equivalent-in-objective-c

반응형