[英]How do I define and use an ENUM in Objective-C?
我在實現文件中聲明了一個枚舉,如下所示,並在我的接口中將該類型的變量聲明為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
必須位於頭文件(或其他#import
到頭文件中)中,因為否則編譯器將不知道將PlayerState
ivar設置為什么大小。 除此之外,我覺得還可以。
在.h中:
typedef enum {
PlayerStateOff,
PlayerStatePlaying,
PlayerStatePaused
} PlayerState;
對於當前的項目,您可能需要使用NS_ENUM()
或NS_OPTIONS()
宏。
typedef NS_ENUM(NSUInteger, PlayerState) {
PLAYER_OFF,
PLAYER_PLAYING,
PLAYER_PAUSED
};
這就是Apple如何為NSString之類的類實現的:
在頭文件中:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.