Enum Values to Nsstring (Ios)

enum Values to NSString (iOS)

This is answered here: a few suggestions on implementation

The bottom line is Objective-C is using a regular, old C enum, which is just a glorified set of integers.

Given an enum like this:

typedef enum { a, b, c } FirstThreeAlpha;

Your method would look like this:

- (NSString*) convertToString:(FirstThreeAlpha) whichAlpha {
NSString *result = nil;

switch(whichAlpha) {
case a:
result = @"a";
break;
case b:
result = @"b";
break;
case c:
result = @"c";
break;

default:
result = @"unknown";
}

return result;
}

Best way to enum NSString

OK, I answered myself. Guess I make a mistake.

This is the new feature I mentioned above:

typedef enum Language : NSUInteger{
ObjectiveC,
Java,
Ruby,
Python,
Erlang
}Language;

It's just a new syntax for enum in Xcode 4.4, but I'm so foolish to think we can exchange "NSUInteger" to "NSString".

So here is the way I found that works:

http://longweekendmobile.com/2010/12/01/not-so-nasty-enums-in-objective-c/

// Place this in your .h file, outside the @interface block
typedef enum {
JPG,
PNG,
GIF,
PVR
} kImageType;
#define kImageTypeArray @"JPEG", @"PNG", @"GIF", @"PowerVR", nil

...

// Place this in the .m file, inside the @implementation block
// A method to convert an enum to string
-(NSString*) imageTypeEnumToString:(kImageType)enumVal
{
NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
return [imageTypeArray objectAtIndex:enumVal];
}

// A method to retrieve the int value from the NSArray of NSStrings
-(kImageType) imageTypeStringToEnum:(NSString*)strVal
{
NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
NSUInteger n = [imageTypeArray indexOfObject:strVal];
if(n < 1) n = JPG;
return (kImageType) n;
}

FYI. The original author of the second example code created a category for enum handling. Just the thing for adding to your very own NSArray class definition.

@interface NSArray (EnumExtensions)

- (NSString*) stringWithEnum: (NSUInteger) enumVal;
- (NSUInteger) enumFromString: (NSString*) strVal default: (NSUInteger) def;
- (NSUInteger) enumFromString: (NSString*) strVal;

@end

@implementation NSArray (EnumExtensions)

- (NSString*) stringWithEnum: (NSUInteger) enumVal
{
return [self objectAtIndex:enumVal];
}

- (NSUInteger) enumFromString: (NSString*) strVal default: (NSUInteger) def
{
NSUInteger n = [self indexOfObject:strVal];
if(n == NSNotFound) n = def;
return n;
}

- (NSUInteger) enumFromString: (NSString*) strVal
{
return [self enumFromString:strVal default:0];
}

@end

How to convert a Swift enum: String into an Objective-C enum: NSString?

NSString * const ISO8601DateFormatType = @"ISO8601";
NSString * const DotNetDateFormatType = @"DotNet";
NSString * const RSSDateFormatType = @"RSS";
NSString * const AltRSSDateFormatType = @"AltRSS";
NSString * const CustomDateFormatType = @"Custom";

NSString * const ISOFormatYear = @"yyyy";
NSString * const ISOFormatYearMonth = @"yyyy-MM"; // 1997-07
NSString * const ISOFormatDate = @"yyyy-MM-dd"; // 1997-07-16
NSString * const ISOFormatDateTime = @"yyyy-MM-dd'T'HH:mmZ"; // 1997-07-16T19:20+01:00
NSString * const ISOFormatDateTimeSec = @"yyyy-MM-dd'T'HH:mm:ssZ"; // 1997-07-16T19:20:30+01:00
NSString * const ISOFormatDateTimeMilliSec = @"yyyy-MM-dd'T'HH:mm:ss.SSSZ"; // 1997-07-16T19:20:30.45+01:00

@interface DateFormat : NSObject

+ (instancetype) ISODateFormat: (NSString *) isoFormat;
+ (instancetype) DotNetDateFormat;
+ (instancetype) RSSDateFormat;
+ (instancetype) AltRSSDateFormat;
+ (instancetype) CustomDateFormat: (NSString *) formatString;

@property (readonly) NSString *dateFormatType;
@property (readonly) NSString *formatDetails;

@end

@implementation DateFormat

- (instancetype) initWithType: (NSString *) formatType details: (NSString *) details {

if(self = [super init]) {
_dateFormatType = formatType;
_formatDetails = details;
}

return self;
}

+ (instancetype) ISODateFormat: (NSString *) isoFormat
{
return [[DateFormat alloc] initWithType: ISO8601DateFormatType details: isoFormat];
}

+ (instancetype) DotNetDateFormat
{
return [[DateFormat alloc] initWithType: DotNetDateFormatType details: nil];
}

+ (instancetype) RSSDateFormat
{
return [[DateFormat alloc] initWithType: RSSDateFormatType details: nil];
}

+ (instancetype) AltRSSDateFormat
{
return [[DateFormat alloc] initWithType: AltRSSDateFormatType details: nil];
}

+ (instancetype) CustomDateFormat: (NSString *) formatString
{
return [[DateFormat alloc] initWithType: CustomDateFormatType details: formatString];
}

@end

Objective-C - Using Enum identifiers as string

Unfortunately this is just not possible using Objective-C. However, it is in Swift if you can use Swift instead.

This is historically handled in Apple's code with NSString constants. For example:

UIKIT_EXTERN NSString *const NSFontAttributeName NS_AVAILABLE_IOS(6_0);

If you need to map between the int value and the NSString value, you will need to write a mapping function.

Also, do make sure to prefix your enums and string constants!

Objective-c: NSString to enum

Rather than use an array, why not use a dictionary; You have the colour NSString as keys, and you return whatever NSNumber you want. Something like; (Long winded for clarity).

NSDictionary *carColourDictionary = @{@"Red": @1,
@"Blue": @2,
@"White": @3};

// Use the dictionary to get the number
// Assume you have a method that returns the car colour as a string:
// - (NSString *)colourAsString;
int carColour = carColourDictionary[object colourAsString];

Convert objective-c typedef to its string equivalent

This is really a C question, not specific to Objective-C (which is a superset of the C language). Enums in C are represented as integers. So you need to write a function that returns a string given an enum value. There are many ways to do this. An array of strings such that the enum value can be used as an index into the array or a map structure (e.g. an NSDictionary) that maps an enum value to a string work, but I find that these approaches are not as clear as a function that makes the conversion explicit (and the array approach, although the classic C way is dangerous if your enum values are not continguous from 0). Something like this would work:

- (NSString*)formatTypeToString:(FormatType)formatType {
NSString *result = nil;

switch(formatType) {
case JSON:
result = @"JSON";
break;
case XML:
result = @"XML";
break;
case Atom:
result = @"Atom";
break;
case RSS:
result = @"RSS";
break;
default:
[NSException raise:NSGenericException format:@"Unexpected FormatType."];
}

return result;
}

Your related question about the correct syntax for an enum value is that you use just the value (e.g. JSON), not the FormatType.JSON sytax. FormatType is a type and the enum values (e.g. JSON, XML, etc.) are values that you can assign to that type.

Convert NS_OPTIONS enum (UIRemoteNotificationType) bitmask to NSString delimited value

Here is the solution I came up with, reasonably terse, but still type specific and brittle to future expansion:

from UIApplication.h typedef NS_OPTIONS(NSUInteger, UIRemoteNotificationType) {
UIRemoteNotificationTypeNone = 0,
UIRemoteNotificationTypeBadge = 1 << 0,
UIRemoteNotificationTypeSound = 1 << 1,
UIRemoteNotificationTypeAlert = 1 << 2,
UIRemoteNotificationTypeNewsstandContentAvailability = 1 << 3, } NS_ENUM_AVAILABLE_IOS(3_0);

NSString* remoteNotificationTypesToString(UIRemoteNotificationType notificationTypes)
{
NSArray *remoteNotificationTypeStrs = @[@"Badge", @"Sound", @"Alert", @"NewsStand"];
NSMutableArray *enabledNotificationTypes = [[NSMutableArray alloc] init];

#define kBitsUsedByUIRemoteNotificationType 4
for (NSUInteger i=0; i < kBitsUsedByUIRemoteNotificationType; i++) {
NSUInteger enumBitValueToCheck = 1 << i;
if (notificationTypes & enumBitValueToCheck)
[enabledNotificationTypes addObject:[remoteNotificationTypeStrs objectAtIndex:i]];
}

NSString *result = enabledNotificationTypes.count > 0 ?
[enabledNotificationTypes componentsJoinedByString:@":"] :
@"NotificationsDisabled";

return result;
}

UIRemoteNotificationType notificationTypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
NSString *notificationTypesStr = remoteNotificationTypesToString(notificationTypes);
NSLog(@"Notification types: %@", notificationTypesStr);

How to make a Swift String enum available in Objective-C?

From the Xcode 6.3 release notes (emphasis added):

Swift Language Enhancements

...

Swift enums can now be exported to Objective-C using the @objc
attribute. @objc enums must declare an integer raw type, and cannot be
generic or use associated values. Because Objective-C enums are not
namespaced, enum cases are imported into Objective-C as the
concatenation of the enum name and case name.

Swift: Convert enum value to String?

Not sure in which Swift version this feature was added, but right now (Swift 2.1) you only need this code:

enum Audience : String {
case public
case friends
case private
}

let audience = Audience.public.rawValue // "public"

When strings are used for raw values, the implicit value for each case
is the text of that case’s name.

[...]

enum CompassPoint : String {
case north, south, east, west
}

In the example above, CompassPoint.south has an implicit raw value of
"south", and so on.

You access the raw value of an enumeration case with its rawValue
property:

let sunsetDirection = CompassPoint.west.rawValue
// sunsetDirection is "west"

Source.



Related Topics



Leave a reply



Submit