[英]Assign Enum to Variable in Objective-C
如何為變量分配枚舉並在以后訪問其值? 我認為這將非常簡單,但每次我嘗試將enum
值分配給變量時(Xcode中沒有類型不匹配或警告出現)我的應用程序崩潰時出現EXC_BAD_ACCESS錯誤。
以下是我在頭文件( BarTypes.h
)中設置enum
:
typedef enum {
BarStyleGlossy,
BarStyleMatte,
BarStyleFlat
} BarDisplayStyle;
沒有問題(至少閱讀和使用這些值)。 但是,當我創建一個可以存儲其中一個enum
值的變量( BarStyleGlossy , BarStyleMatte或BarStyleFlat )然后嘗試設置該變量時,應用程序崩潰了。 以下是我設置和使用變量的方法:
//Header
@property (nonatomic, assign, readwrite) BarDisplayStyle barViewDisplayStyle; //I've also tried just using (nonatomic) and I've also tried (nonatomic, assign)
//Implementation
@synthesize barViewDisplayStyle;
- (void)setupBarStyle:(BarDisplayStyle)displayStyle {
//This is where it crashes:
self.barViewDisplayStyle = displayStyle;
}
為什么會在這里崩潰? 如何將枚舉的值存儲在變量中? 我認為這個問題與我最終對enums
缺乏了解有關,但是如果我遵循傳統的變量設置和分配等,這應該有效。 關於我做錯了什么的任何想法?
請注意,我是enum
的新手,所以我的詞匯可能有點混亂(原諒我 - 如果你知道我想說的話,可以自由編輯)。
我在網上發現了一些關於enums
引用:
編輯:這是我如何調用setupBarStyle
方法:
BarView *bar = [[BarView alloc] init];
[bar setupBarStyle:displayStyle];
以防有人在那里仍然試圖找出如何將枚舉值分配給枚舉類型的變量或屬性...這是一個使用屬性的示例。
在頭文件中......
@interface elmTaskMeasurement : NSObject
typedef NS_ENUM(NSInteger, MeasurementType) {
D,
N,
T,
Y,
M
};
@property(nonatomic) MeasurementType MeasureType;
@end
在創建對象的文件中...
elmTaskMeasurement *taskMeasurement = [[elmTaskMeasurement alloc] init];
taskMeasurement.MeasureType = (MeasurementType)N;
您實現的方法稱為setupBarStyle:
,但您在對象上調用setupBarShape:
我自己有這個錯誤,但錯誤是由於我當然創造了自己的不同錯誤造成的。
我的屬性“myApplicationState”的setter如下:
-(void)setApplicationStyle:(myApplicationStyle)applicationStyle{
self.applicationStyle = applicationStyle;
//some more code
}
當然,這將導致無限循環,因為在設置器中,再次,再次,再次調用設置。
它必須是:
-(void)setApplicationStyle:(myApplicationStyle)applicationStyle{
_applicationStyle = applicationStyle;
//some more code
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.