Converting string to static constant - objective-c

I have in my objective-c application a number of constants that I need to have inputted from an external source using strings. The reason of course, is that constants are better to work with, but can't be passed external.
I have made this objective-c code to convert, and it works 100%, but a) it is ugly, and b) quite obscure. I suppose I could have converted to NSNumber and made an array, but that seems like a lot of code/processing (though maybe the right solution)
Can anyone provide a better solution?
NSArray *types = #[#"text_input",#"textbox",#"select",#"yesno",#"date",#"signature",#"label",#"SectionHeading"];
int indexes[10];
indexes[0] = FieldTypeTextInput;
indexes[1] = FieldTypeTextBox;
indexes[2] = FieldTypeSelect;
indexes[3] = FieldTypeYesNo;
indexes[4] = FieldTypeDate;
indexes[5] = FieldTypeSignature;
indexes[6] = FieldTypeLabel;
indexes[7] = FieldTypeSectionHeading;
for (int i=0;i<[types count];i++)
{
NSString *string_i = [types objectAtIndex:i];
if ([type_string isEqualToString:string_i])

I suggest to use an NSDictionary.
enum YourNiceTypes : NSInteger {FieldNotFound, FieldTypeTextInput, FieldTypeTextBox, ...};
NSDictionary *types = #{"text_input" : #(FieldTypeTextInput), ... };
enum YourNiceType type = [types[textInput] integerValue];
You used the trick to define wrong input with zero, which will be handled automatically correctly, as calling integerValue on a nil object will return 0.

Related

Storing and retrieving enums from NSArray

I'm a beginner obj-c programmer. I want to store enums in an NSMutableArray, then retrieve them.
I do this by first converting the enum to NSNumber object then storing that object into the array, and then retrieving it and converting it back to an integer. I have code that does it without arrays, and works, but I need to use an array.
Code:
//What I am trying to do:
NSNumber *n = [NSNumber numberWithInt:west];
[DirectionList addObject:n];
Direction intendedDirection = [[DirectionList objectAtIndex:0] intValue];
if (intendedDirection == west)
{
exit(-1); // DOES NOT EXIT, BUT SHOULD
}
//This code works, though
NSNumber *n = [NSNumber numberWithInt:west];
Direction intendedDirection = [n intValue];
if (intendedDirection == west)
{
exit(-1); // EXITS AS EXPECTED
}
Any ideas why the 1st one doesn't work?
Thanks.
If you don't need to mutate the array, I suggest you this method which is much, much cleaner than the one you're trying to follow.
I'm using NSString for this example but you can use any object you want
typedef NS_ENUM(NSUInteger, Direction) {
North,
South,
West,
East
};
NSString *const directionDescriptions[] = {
[West] = #"West",
[East] = #"East",
[North] = #"North",
[South] = #"South",
}
Then you can access your description using the enum as the index of this array.
// E.g.
NSSLog(#"%#", directionDescriptions[West]); // #"West"

ReConvert NSString to NSArray

I have converted an NSArray to NSString using below code
Suppose i have an array with some data in it.
NSString *sample=[array description];
NSLog(#"%#",sample);
which prints:
(
{
URL = "1a516af1a1c6020260a876231955e576202bbe03.jpg##37911944cc1ea8fd132ee9421a7b3af326afcc19.jpg";
userId = 0;
wallpaperId = 31;
},
{
URL = "a9356863fa43bc3439487198283321622f88e31f.jpg##f09c743ebdc26bb9f98655310a0529b65a472428.jpg";
userId = 0;
wallpaperId = 30;
}
)
It looks like array but it is actually a string.
Now I am wondering, how can I reconvert back to NSArray?
Help appreciated.
And please this not a duplicate question, I couldn't found the same anywhere on SO.
You cannot rely on the results of description as it is not a convert to string operator, but merely a debugging aid. There is nothing to stop it changing between O/S releases and there is no equivalent fromDescription method.
The conventional way of serializing an Objective-C collection to and from a string is to use JSON, so look at the NSJSONSerialization class.
the
NSString componentsseparatedbystring
method will return an array of components separated by a string

Converting a string variable from Binary to Decimal in Objective C

Im trying to create a Binary to Decimal calculator and I am having trouble doing any sort of conversion that will actually work. First off Id like to introduce myself as a complete novice to objective c and to programming in general. As a result many concepts will appear difficult to me, so I am mostly looking for the easiest way to understand and not the most efficient way of doing this.
I have at the moment a calculator that will accept input and display this in a label. This part is working fine and I have no issues with it. The variable that the input is stored on is _display = [[NSMutableString stringWithCapacity:20] retain];
this is working perfectly and I am able to modify the data accordingly. What I would like to do is to be able to display an NSString of the conversion in another label. At the moment I have tried a few solutions and have not had any decent results, this is the latest attempt
- (NSMutableString *)displayValue2:(long long)element
{
_str= [[NSMutableString alloc] initWithString:#""];
if(element > 0){
for(NSInteger numberCopy = element; numberCopy > 0; numberCopy >>= 1)
{
[_str insertString:((numberCopy & 1) ? #"1" : #"0") atIndex:0];
}
}
else if(element == 0)
{
[_str insertString:#"0" atIndex:0];
}
else
{
element = element * (-1);
_str = [self displayValue2:element];
[_str insertString:#"0" atIndex:0];
NSLog(#"Prima for: %#",_str);
for(int i=0; i<[_str length];i++)
_str = _display;
NSLog(#"Dopo for: %#",_str);
}
return _str;
}
Within my View Controller I have a convert button setup, when this is pressed I want to set the second display field to the decimal equivalent. This is working as if I set displayValue2 to return a string of my choosing it works. All I need is help getting this conversion to work. At the moment this bit of code has led to "incomplete implementation" being displayed at the to of my class. Please help, and cheers to those who take time out to help.
So basically all you are really looking for is a way to convert binary numbers into decimal numbers, correct? Another way to think of this problem is changing a number's base from base 2 to base 10. I have used functions like this before in my projects:
+ (NSNumber *)convertBinaryStringToDecimalNumber:(NSString *)binaryString {
NSUInteger totalValue = 0;
for (int i = 0; i < binaryString.length; i++) {
totalValue += (int)([binaryString characterAtIndex:(binaryString.length - 1 - i)] - 48) * pow(2, i);
}
return #(totalValue);
}
Obviously this is accessing the binary as a string representation. This works well since you can easily access each value over a number which is more difficult. You could also easily change the return type from an NSNumber to some string literal. This also works for your element == 0 scenario.
// original number wrapped as a string
NSString *stringValue = [NSString stringWithFormat:#"%d", 11001];
// convert the value and get an NSNumber back
NSNumber *result = [self.class convertBinaryStringToDecinalNumber:stringValue];
// prints 25
NSLog(#"%#", result);
If I misunderstood something please clarify, if you do not understand the code let me know. Also, this may not be the most efficient but it is simple and clean.
I also strongly agree with Hot Licks comment. If you are truly interested in learning well and want to be an developed programmer there are a few basics you should be learning first (I learned with Java and am glad that I did).

NSString (or NSArray or something) to variable parameter list of C (char *) strings

Is there any easy way to convert an Objective-C holding class of NSStrings into parameters for a function accepting a variable list of char *? Specifically I have a function like:
-(void)someFunction:(NSSomething *) var
that I want to forward to a C function like
void someCFunction(char * var, ...)
Is there an easy way to go about this?
No, you can only do what you want if the number of arguments you're passing is known at compile time. If you just want to convert a single string, use the -UTF8String message:
// Example with two strings
NSString *str1 = ...;
NSString *str2 = ...;
someCFunction([str1 UTF8String], [str2 UTF8String]); // etc.
But if the number of strings will vary at runtime, you'll need to use a different API, if one is available. For example, if there's an API that took an array of strings, you could convert the Objective-C array into a C array:
// This function takes a variable number of strings. Note: in C/Objective-C
// (but not in C++/Objective-C++), it's not legal to convert 'char **' to
// 'char *const *', so you may sometimes need a cast to call this function
void someCFunction(const char *const *stringArray, int numStrings)
{
...
}
...
// Convert Objective-C array to C array
NSArray *objCArray = ...;
int numStrings = [objCArray count];
char **cStrArray = malloc(numStrings * sizeof(char*));
for (int i = 0; i < count; i++)
cStrArray[i] = [[objCArray objectAtIndex:i] UTF8String];
// Call the function; see comment above for note on cast
someCFunction((const char *const *)cStrArray, numStrings);
// Don't leak memory
free(cStrArray);
This would do the trick:
NSString *string = #"testing string"
const char * p1=[string UTF8String];
char * p2;
p2 = const_cast<char *>(p1);
Yes, this can be done, and is explained here:
How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
And here:
http://www.cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html
With modifications for ARC here:
How to create a NSString from a format string like #"xxx=%#, yyy=%#" and a NSArray of objects?
Also, variable arguments are not statically or strongly typed, as the other poster seems to be suggesting. In fact, there is no clear indication in the callee of how many arguments you really have. Determining the number of arguments generally breaks down into having to either specify the number by an count parameter, using a null terminator, or inferring it from a format string a la (s)print* . This is frankly why the C (s)print* family of functions has been the source of many errors, now made much much safer by the XCode / Clang / GCC compiler that now warns.
As an aside, you can approach statically typed variable arguments in C++ by creating a template method that accepts an array of an unspecified size. This is generally considered bad form though as the compiler generates separate instances for each size of array seen by by the compiler (template bloat).

Map char to int in Objective-C

I have a need to map char values to int values in Objective-C. I know NSDictionary is out because it deals with reference types, and these are values. The map will be used while iterating through an NSString. Each character in the string will be converted to an integer value. All the integers will be summed together.
Using NSDictionary seems like a bad fit because of all the type coercion I'd have to do. (Converting values types, char and int, to reference types.)
I figure I'll have to drop down to C to do this, but my experience with C libraries is very limited.
Is there something most C developers use that will map char values to int values?
Edit for clarification
The C# equivalent would be a Dictionary<char,int>.
In pseudocode, I'd like to the following:
for (int i = 0; i < [string length]; i++) {
char current = [string characterAtIndex:i];
int score = map[current]; // <- I want map without boxing
// do something with score
}
Char to int?
char aChar = 'a';
int foo = (int) aChar;
Done. No need for a hash or anything else. Even if you wanted to map char -> NSNumber, an array of 256 char's (char being a signed 8 bit type) is very little overhead.
(Unless I entirely misparsed your question -- are you asking for (char*)? ... i.e. C strings? Show some code.).
If I understand correctly, you want to store chars and ints in a dictionary, as keys and values. However, NSDictionary only accepts objects. The solution? Wrap the chars and ints in the NSNumber object:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:1],
[NSNumber numberWithChar:'a'],
[NSNumber numberWithInt:2],
[NSNumber numberWithChar:'b'],
nil];
Or if you don't want boxing, why not just make a function that takes chars and returns ints?
int charToScore(char character)
{
switch (character) {
case 'a':
return 1;
case 'b':
return 2;
default:
return 0;
}
}
#Pontus has the correct answer in Objective-C, but if you're willing to use C++, you can use std::map<char, int> (or the still-slightly-nonstandard unordered_map<char, int>.)
To use C++ from within Objective-C, you must rename the file from Whatever.m to Whatever.mm--this tells GCC that the file contains Objective-C++, which allows you to use the Objective-C syntax with C++ underpinnings.