NSStringEncoding - enum to string to enum - objective-c

So I'm saving the NSString encoding enum value in a database as a string. This is one of the values:
NSUTF16LittleEndianStringEncoding = 0x94000100,
And I'm saving it as a string with value 0x94000100. My goal is to read this value as an NSString, but then turn it into a value I can use to encode:
NSString* encodingValueAsString = [object objectForKey:kWSWordlistFilesEncodingKey];
// Convert 'encodingValueAsString' to variable 'encoding' that can act as enum
NSString* dataString = [[NSString alloc] initWithData:data
encoding:encoding];
How do I write that missing line?

There's no reason to convert the enum value to/from a string. Just save it and read it back as an int.
But the short answer to your original question is:
NSStringEncoding encoding = [encodingValueAsString intValue];
Wait - that won't work since you are saving the string as the hex value.
You need to use NSScanner:
NSScanner *scanner = [NSScanner scannerWithString:encodingValueAsString];
NSStringEncoding encoding;
[scanner scanHexInt:&encoding];
See why using int instead of a string would be easier?

Related

How do you convert an entity's attribute of type int16 to string to be output to the user?

I have tried different methods for converting a value of type integer 16 to a string but none work. When an entity returns a numerical value, is it of a different type than what it is?
NSString *stringToGoOut =[#[entity valueForKey:#"value1"] stringValue];
NSString *stringToGoOut2 = [NSString stringWithFormat:#"%i", [entity valueForKey:#"value2"]];
the second one shows an error saying that the formate specifies type 'int' but the argument has type 'id_Nullable and request that i change the place holder from %i to %# for string but when i do that, it outputs 0 overtime regardless of what has been entered on the previous screen
NSString *stringToGoOut2 = [NSString stringWithFormat:#"%ld", (long)[entity valueForKey:#"value2"]];
this worked sort of, but the output was a long number (i am guessing the location in memory) to the user.
valueForKey: returns an object so to convert to a string either
NSString *stringToGoOut = [NSString stringWithFormat:#"%#", [entity valueForKey:#"value1"]];
or
NSString *stringToGoOut = [[entity valueForKey:#"value1"] stringValue];
will work.
If it is outputting 0 then [entity valueForKey:#"value1"] is probably an NSNumber
Core data stores all the numbers as NSNumber.
So if you would like to print out the value this line should work
NSString *stringToGoOut = [NSString stringWithFormat:#"%#", entity.value1];

Detect type from string objective-c

Whats the best way of detecting a data type from a string in Objective-c?
I'm importing CSV files but each value is just a string.
E.g. How do I tell that "2.0" is a number, "London" should be treated as a category and that "Monday 2nd June" or "2/6/2012" is a date.
I need to test the datatype some how and be confident about which type I use before passing the data downstream.
Regex is the only thing I can think about, but if you are on mac or iphone, than you might try e.g. RegexKitLite
----------UPDATE----------
Instead of my previous suggestion, try this:
NSString *csvString = #"333";
NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,";
NSScanner *typeScanner = [NSScanner scannerWithString: csvString];
[typeScanner setCharactersToBeSkipped: [NSCharacterSet characterSetWithCharactersInString:charSet]];
NSString *checkString = [[NSString alloc] init];
[typeScanner scanString:csvString intoString:&checkString];
if([csvString length] == [checkString length]){
//the string "csvString" is an integer
}
To check for other types (float, string, etc.), change this line (which checks for int type) NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.,"; to NSString *charSet = #"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; (which checks for float type) or NSString *charSet = #"1234567890"; (which checks for a string composed only of letters).
-------Initial Post-------
You could do this:
NSString *stringToTest = #"123";
NSCharacterSet *intValueSet = [NSCharacterSet decimalDigitCharacterSet];
NSArray *test = [stringToTest componentsSeparatedByCharactersInSet:intValueSet];
if ([test count]==[stringToTest length]+1){
NSLog(#"It's an int!");
}
else {
NSLog(#"It's not an int");
}
This works for numbers that don't have a decimal point or commas as thousands separators, like "8493" and "883292837". I've tested it and it works.
Hope this provides a start for you! I'll try to figure out how to test for numbers with decimal points and strings.
Like Andrew said, regular expressions are probably good for this, but they're a bit complicated.

Get Unicode point of NSString and put that into another NSString

What's the easiest way to get the Unicode value from an NSString? For example,
NSString *str = "A";
NSString *hex;
Now, I want to set the value of hex to the Unicode value of str (i.e. 0041)... How would I go about doing that?
The unichar type is defined to be a 16-bit unicode value (eg, as indirectly documented in the description of the %C specifier), and you can get a unichar from a given position in an NSString using characterAtIndex:, or use getCharacters:range: if you want to fill a C array of unichars from the NSString more quickly than by querying them one by one.
NSUTF32StringEncoding is also a valid string encoding, as are a couple of endian-specific variants, in case you want to be absolutely future proof. You'd get a C array of those using the much more longwinded getBytes:maxLength:usedLength:encoding:options:range:remainingRange:.
EDIT: so, e.g.
NSString *str = #"A";
NSLog(#"16-bit unicode values are:");
for(int index = 0; index < [str length]; index++)
NSLog(#"%04x", [str characterAtIndex:index]);
You can use
NSData * u = [str dataUsingEncoding:NSUnicodeStringEncoding];
NSString *hex = [u description];
You may replace NSUnicodeStringEncoding by NSUTF8StringEncoding, NSUTF16StringEncoding (the same as NSUnicodeStringEncoding) or NSUTF32StringEncoding, or many other values.
See here
for more

NSString to char[]?

struct DATA
{
unsigned char USERNAME[32];
};
i want copy a NSString to struct DATA.USERNAME , how to do it ?
You can use the -[NSString UTF8String] method to get a C string of your NSString. Then, you can use strncpy(DATA.USERNAME, [mystring UTF8String], 32); to copy that string into the structure.
You first need to know what encoding is expected. NSString can generate bytes in a wide range of encodings. Then you pass a pointer to the USERNAME array to getCString:maxLength:encoding:. So, for example, if you want to copy the contents of the NSString myCocoaString as UTF-8 into USERNAME field of a DATA struct called myData, you'd do:
BOOL success = [myCocoaString getCString:myData.USERNAME maxLength:32 encoding:NSUTF8StringEncoding];
NSLog(#"Was %# to store string contents in USERNAME!", success ? #"able" : #"not able");

Converting long value to unichar* in objective-c

I'm storing large unicode characters (0x10000+) as long types which eventually need to be converted to NSStrings. Smaller unicode characters can be created as a unichar, and an NSString can be created using
[NSString stringWithCharacters:(const unichar *)characters length:(NSUInteger)length]
So, I imagine the best way to get an NSString from the unicode long value would be to first get a unichar* from the long value. Any idea on how I might go about doing this?
Is there any reason you are storing the values as longs? For Unicode storage you only need to store the values as UInt32, which would then make it easy to interpret the data as UTF-32 by doing something like this:
int numberOfChars = 3;
UInt32* yourStringBuffer = malloc(sizeof(UInt32) * numberOfChars);
yourStringBuffer[0] = 0x2F8DB; //杞
yourStringBuffer[1] = 0x2318; //⌘
yourStringBuffer[2] = 0x263A; //☺
NSData* stringData = [NSData dataWithBytes:yourStringBuffer length:sizeof(UInt32) * numberOfChars];
//set the encoding according to the current byte order
NSStringEncoding encoding;
if(CFByteOrderGetCurrent() == CFByteOrderBigEndian)
encoding = NSUTF32BigEndianStringEncoding;
else
encoding = NSUTF32LittleEndianStringEncoding;
NSString* string = [[NSString alloc] initWithData:stringData encoding:encoding];
free(yourStringBuffer);
NSLog(#"%#",string);
//output: 杞⌘☺