programing

Objective-C에서 ENUM을 정의하고 사용하려면 어떻게 해야 합니까?

minecode 2022. 7. 11. 22:11
반응형

Objective-C에서 ENUM을 정의하고 사용하려면 어떻게 해야 합니까?

아래 그림과 같이 구현 파일에 열거형을 선언하고 해당 유형의 변수를 인터페이스 내에 PlayerState thePlayerState로 선언하고 메소드에 변수를 사용했습니다.하지만 미신고라는 오류가 발생하고 있습니다.메서드에서 PlayerState 유형의 변수를 올바르게 선언하고 사용하려면 어떻게 해야 합니다.

.m 파일

@implementation View1Controller

    typedef enum playerStateTypes
        {
            PLAYER_OFF,
            PLAYER_PLAYING,
            PLAYER_PAUSED
        } PlayerState;

.h 파일:

@interface View1Controller : UIViewController {

    PlayerState thePlayerState;

.m 파일의 어떤 방법으로든:

-(void)doSomethin{

thePlayerState = PLAYER_OFF;

}

Apple은 Swift를 포함한 더 나은 코드 호환성을 제공하는 데 도움이 되는 매크로를 제공합니다.매크로를 사용하는 방법은 다음과 같습니다.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

여기에 기재되어 있습니다.

당신의.typedef헤더 파일(또는 다른 파일)에 존재해야 합니다.#imported in your header)를 입력하지 않으면 컴파일러는 어떤 사이즈를 작성해야 하는지 알 수 없기 때문입니다.PlayerState아이바, 그것 빼고는 괜찮아 보이는데요

.h:

typedef enum {
    PlayerStateOff,
    PlayerStatePlaying,
    PlayerStatePaused
} PlayerState;

현재 프로젝트에서는NS_ENUM()또는NS_OPTIONS()매크로를 선택합니다.

typedef NS_ENUM(NSUInteger, PlayerState) {
        PLAYER_OFF,
        PLAYER_PLAYING,
        PLAYER_PAUSED
    };

NSString과 같은 클래스에서 Apple은 다음과 같이 합니다.

헤더 파일:

enum {
    PlayerStateOff,
    PlayerStatePlaying,
    PlayerStatePaused
};

typedef NSInteger PlayerState;

http://developer.apple.com/에 있는 코딩 가이드라인을 참조해 주세요.

NS_OPTIONS 또는 NS_ENUM 사용을 권장합니다.자세한 것은, http://nshipster.com/ns_enum-ns_options/ 를 참조해 주세요.

NS_OPTIONS를 사용한 자체 코드의 예를 다음에 나타냅니다.UIView의 레이어에 서브레이어(CALayer)를 설정하여 경계를 작성하는 유틸리티가 있습니다.

h. 파일:

typedef NS_OPTIONS(NSUInteger, BSTCMBorder) {
    BSTCMBOrderNoBorder     = 0,
    BSTCMBorderTop          = 1 << 0,
    BSTCMBorderRight        = 1 << 1,
    BSTCMBorderBottom       = 1 << 2,
    BSTCMBOrderLeft         = 1 << 3
};

@interface BSTCMBorderUtility : NSObject

+ (void)setBorderOnView:(UIView *)view
                 border:(BSTCMBorder)border
                  width:(CGFloat)width
                  color:(UIColor *)color;

@end

.m 파일:

@implementation BSTCMBorderUtility

+ (void)setBorderOnView:(UIView *)view
                 border:(BSTCMBorder)border
                  width:(CGFloat)width
                  color:(UIColor *)color
{

    // Make a left border on the view
    if (border & BSTCMBOrderLeft) {

    }

    // Make a right border on the view
    if (border & BSTCMBorderRight) {

    }

    // Etc

}

@end

언급URL : https://stackoverflow.com/questions/2212080/how-do-i-define-and-use-an-enum-in-objective-c

반응형