Reputation: 3253
I have started learning iOS development.
I want to use enum
in my sample project.
I've declared enum
in sample.h
like following. I hope I've declared this correctly.
typedef enum{s=1,m,t,w,th,f,sa} days;
I want to use this in viewController.m
. In viewController.h,
I've imported sample.h
.
I want to use enum with the name like "days.sa"
. But more code i searched in google, they've said like create a instance variable in "sample.h"
like
@interface Sample:NSObject
{
days d;
}
If I want to use this means, I need to create and use instance. But I don't want like that.
I need to use like
days.d or days.sa or days.th
How to do that ?, This must be used for the whole Project and
How to create enum as class variable instead of instance variable ?
Upvotes: 30
Views: 42731
Reputation: 534
Creating Enum in Enumrations.h
typedef enum
{
Atype = 1,
Btype,
Ctype,
Dtype,
Etype,
}type;
Where ever you want to user this enum just import Enumrations.h, and you can use Atype without creating type object.
you can simply use NSLog(@"%@",@(Atype))
.
Upvotes: 4
Reputation: 440
#import <Foundation/Foundation.h>
typedef enum{
s=1,m,t,w,th,f,sa
} days;
@interface weekday : NSObject
@property (nonatomic, assign) days day;
@end
@implementation weekday
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
weekday *sunDay=[[weekday alloc]init];
sunDay.day=s;
NSLog(@"Today is %d",sunDay.day);
}
return 0;
}
Upvotes: 5
Reputation: 3663
hey you use enum like this here is an example
In .h define enum
typedef enum{s=1,m,t,w,th,f,sa} days;
In .m play with enum element like this
days d1 =f;
switch (d1) {
case m:
case t:
NSLog(@"You like Tuesday");
break;
case w:
case th:
break;
case f:
NSLog(@"You like friday");
break;
case sa:
NSLog(@"You satureday");
break;
case s:
NSLog(@"You like sunday");
break;
default:
break;
}
if you want learn more click this.
Upvotes: 10
Reputation: 4554
In the enum you've created, s
, m
etc. are now available globally (i.e. to anything that imports sample.h
). If you want the integer corresponding to Saturday, for example, it's just sa
, not days.sa
. I think you're confusing enums with structures.
For this reason, it's better to use more verbose names in your enum. Something like:
typedef enum
{
WeekdaySunday = 1,
WeekdayMonday,
WeekdayTuesday,
WeekdayWednesday,
WeekdayThursday,
WeekdayFriday,
WeekdaySaturday
} Weekday;
so e.g. WeekdayMonday
is now just another way of writing 2
in your app, but will make your code more readable and pre-defines the possible legal values for a variable of type Weekday
.
The above is fine, but for better compiler support and to ensure the size of a Weekday
, I'd recommend using NS_ENUM
:
typedef NS_ENUM(NSInteger, Weekday)
{
WeekdaySunday = 1,
WeekdayMonday,
WeekdayTuesday,
WeekdayWednesday,
WeekdayThursday,
WeekdayFriday,
WeekdaySaturday
};
Upvotes: 52