Using NSNumber to sort numerous integers - objective-c

Ive been doing alot of research and can't quite grasp resolving this issue. In my application I have several text fields that save integer values in the form of int variables (at least 15 int variables). My main goal is to sort out high to low numbers that were saved from the text fields.
Now would I use the following code to convert each seperate integer variable into a new NSNumber, than use a sort function to sort out the new NSNumbers from high to low?
NSNumber *newNumber = [NSNumber numberWithInt: my_int_variable];
I just feel as if this is a redundant way of sorting 12 integer variables and there is a easier way. Thank you for the help

Going from individual text fields to strings to ints to NSNumbers to an array to a sorted array is long, clunky trip. But a worthwhile trip nevertheless.
// assume these
UITextField *field0;
UITextField *field1;
UITextField *field2;
// make an array for the input and the result
NSArray *textFields = #[field0, field1, field2];
NSMutableArray *numbers = [#[] mutableCopy];
// prepare a number formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
// lots of choices here. see https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/index.html
for (UITextField *textField in textFields) {
NSString *text = textField.text;
NSNumber *number = [formatter numberFromString:text];
[numbers addObject:number];
}
// sort...a few choices here, too. taking the simplest:
[numbers sortUsingSelector:#selector(compare:)];
NSLog(#"ta da: %#", numbers);
Or did you want to sort the text fields based on their contents? Doable too:
NSMutableArray *textFields = [#[field0, field1, field2] mutableCopy];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
[textFields sortedUsingComparator: ^(id objA, id objB) {
NSString *textA = ((UITextField *)objA).text;
NSString *textB = ((UITextField *)objB).text;
NSNumber *numberA = [formatter numberFromString:textA];
NSNumber *numberB = [formatter numberFromString:textB];
return [numberA compare:numberB];
}];
NSLog(#"text fields in order of their contents: %#", textFields);

Related

How to combine two key values in the dictionary of array in Objective C

I am having the multiple objects of the dictionary in the array. Now, in particular dictionary i have two keys "category" and "createdDate" from the other key.
Situation : -
I Need an array which having objects in a such a way that, the category which having the same date can be clubbed together and form an object . and Those category having different date is the other object it self.
I am having situation in my mind where i have to put various comparison conditions between the keys , the basic approach of doing it . --- Not Required
Need your valuable suggestion for Different Approach, Which is required, also is not complex. Thanks in advance.
here you go, an example
NSDateFormatter * df = [NSDateFormatter new];
for (id object in self.mainArray) {
[df setDateFormat:#"MM/dd/yyyy"];
NSString *dateString = [df stringFromDate:[object objectForKey:#"createdDate"]];
NSMutableArray *sectionArray = self.totalsSectionDictionary[dateString];
if (!sectionArray) {
sectionArray = [NSMutableArray array];
self.totalsSectionDictionary[dateString] = sectionArray;
}
NSString * tempString = [object valueForKey:#"category"]
[sectionArray addObject:#{#"value" : tempString}];
}
this results in a dictionary of objects combined by date as a string value and inside each one of those date keys resides an array of values for that date. From there, you need to tease out those values and sort them like so:
NSArray * tempUnsortedArray = [self.totalsSectionDictionary allKeys];
NSArray *arrKeys = [tempUnsortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"MM/dd/yyyy"];
NSDate *d1 = [df dateFromString:(NSString*) obj1];
NSDate *d2 = [df dateFromString:(NSString*) obj2];
return [d2 compare: d1];
}];
NSMutableArray * tempArray1 = [NSMutableArray array];
for (NSInteger i = 0; i < arrKeys.count; i++) {
NSMutableArray *sectionArray = self.totalsSectionDictionary[arrKeys[i]];
}
there you go, the last for loop will allow you to iterate through each section array stored in the original dictionary by date so you can put them into a collection or table view
good luck

Algorithm to convert 1 to "One" and so on in objective-c [duplicate]

This question already has answers here:
How to convert numbers into text?
(8 answers)
Closed 7 years ago.
I'm looking for an algorithm or function to convert integer number 0,1,2 to Zero,One,Two respectively. How can we do this in Objective-C ?
Apple has a lot of handy formatting functionality built in for many data types. Called a "formatter," they can convert objects to/from string representations.
For your case, you will be using NSNumberFormatter, but if you have an integer you need to convert it to an NSNumber first. See below example.
NSInteger anInt = 11242043;
NSString *wordNumber;
//convert to words
NSNumber *numberValue = [NSNumber numberWithInt:anInt]; //needs to be NSNumber!
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
wordNumber = [numberFormatter stringFromNumber:numberValue];
NSLog(#"Answer: %#", wordNumber);
// Answer: eleven million two hundred forty-two thousand forty-three
This is my code for 0 to 100 (You can update as per your requirement). WORKING PERFECTLY !!
-(NSDictionary *)algorithm
{
NSArray *myArray = #[#"Zero",#"One",#"Two",#"Three",#"Four",#"Five",#"Six",#"Seven",#"Eight",#"Nine",#"Ten",#"Eleven",#"Twelve",#"Thirteen",#"Fourteen",#"Fifteen",#"Sixteen",#"Sevteen",#"Eighteen",#"Nineteen"];
NSArray *tensArray = #[#"Twenty",#"Thirty",#"Fourty",#"Fifty",#"Sixty"
,#"Seventy",#"Eighty",#"Ninety",#"One Hundred"];
NSMutableDictionary *numberStringDictionary = [[NSMutableDictionary alloc] init];
NSMutableArray *numberStringsArray = [[NSMutableArray alloc] init];
for(int i=0;i<=100;i++)
{
if(i<20)
{
[numberStringDictionary setObject:myArray[i] forKey:[NSString stringWithFormat:#"%d",i]];
[numberStringsArray addObject:myArray[i]];
NSLog(#"\n%#",myArray[i]);
}
else if(i%10==0)
{
[numberStringDictionary setObject:tensArray[i/10-2] forKey:[NSString stringWithFormat:#"%d",i]];
[numberStringsArray addObject:tensArray[i/10-2]];
NSLog(#"\n%#",tensArray[i/10-2]);
}
else
{
[numberStringDictionary setObject:[NSString stringWithFormat:#"%# %#",tensArray[i/10-2],myArray[i%10]] forKey:[NSString stringWithFormat:#"%d",i]];
[numberStringsArray addObject:[NSString stringWithFormat:#"%# %#",tensArray[i/10-2],myArray[i%10]]];
NSLog(#"%#",[NSString stringWithFormat:#"%# %#",tensArray[i/10-2],myArray[i%10]]);
}
}
return numberStringDictionary;
}

Convert a string to a positive or negative number

I am new to ObjC. I've spent years working in Applescript and I've decided to move up. I am a hobbiest programmer.
I have the following code:
+(NSArray *) initArrayWithFileContents:(NSString *) theFilePath
{
NSString *theContents = [(self) loadFile:theFilePath]; // returns the contents of a text file
NSArray *theParagraphs = [(self) getParagraphs:theContents]; // returns the contents as an array of paragraphs
NSMutableArray *teamData = [[NSMutableArray alloc] init]; // array of team data
NSMutableArray *leagueData = [[NSMutableArray alloc] init]; // array of arrays
NSNumberFormatter *numberStyle = [[NSNumberFormatter alloc] init];
[numberStyle setNumberStyle:NSNumberFormatterDecimalStyle];
for (NSString *currentParagraph in theParagraphs)
{
NSArray *currentTeam = [(self) getcolumnarData:currentParagraph];
for (NSString *currentItem in currentTeam)
{
NSNumber *currentStat = [numberStyle numberFromString:currentItem];
if (currentStat != Nil) {
[teamData addObject:currentStat];
} else {
[teamData addObject:currentItem];
}
}
[leagueData addObject:teamData];
[teamData removeAllObjects];
}
return leagueData;
}
This works fine for strings and for negative numbers, but a number preceded by a "+" sign is returned as a string. I figure I need to use a different number formatter style but I don't know what to use.
Thanks in advance,
Brad
NSNumberFormatter *numberStyle = [[NSNumberFormatter alloc] init];
[numberStyle setNumberStyle:NSNumberFormatterDecimalStyle];
[numberStyle setPositiveFormat:#"'+'#"] ;
or
NSNumberFormatter *numberStyle = [[NSNumberFormatter alloc] init];
[numberStyle setNumberStyle:NSNumberFormatterDecimalStyle];
[numberStyle setPositivePrefix:#"+"] ;
You could remove the + sign if one exists:
if ([currentItem hasPrefix:#"+"])
{
currentItem = [currentItem substringWithRange:NSMakeRange(1, [currentItem length] -1)];
}
Probably a better way, but this would work.
What ended up working for me was to create 2 NSNumberFormatters; 1 for decimals and 1 for decimals using the setPositiveFormat: method as described above. If the first formatter doesn't work, it'll flow on to the next formatter using the positive format.

Format values from a NSArray

I have a NSArray containing several strings that look like this: "291839.0930820"
I would like to format those values in the array so that they show up in my detailTextLabel of a UITableView with only 2 decimals: "291,839.09"
How can I accomplish this?
To properly format numbers so the numbers appear correctly for a given user's domain is to use NSNumberFormatter. You should never usevstringWithFormat: for such purposes.
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]:
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMaximumFractionDigits:2];
NSNumber *val = array[indexPath.row];
NSString *text = [formatter stringFromNumber:val];
Update:
I'm getting the feeling from Juan that the array doesn't actually contain NSNumber objects for the numbers but it actually contains NSString representations of the numbers. If this is the case, then one line in my answer needs to be changed. Change:
NSNumber *val = array[indexPath.row];
to:
NSNumber *val = #([array[indexPath.row] doubleValue]);
This will get the NSString from the array, then get the string's value as a double, and finally wrap the double in an NSNumber.
You could try something like this if your array has float values
cell.detailTextLabel.text=[NSString stringWithFormat:#"%.02f", [[array objectAtIndex:index]floatValue]];
lets say your value is double value = 291839.0930820;
You can construct a string like this
NSString *formattedValue = [NSString stringWithFormat:#"%0.2f",value];
assign this formattedValue to your textfield/label.
cell.textLabel.text = formattedValue;

NSNumberFormatter leading 0's and decimals

Is there any way to format an NSNumber with leading 0's and decimals? For example, I need to have the ability to write 4.5 as well as 000. Currently I have it where it will allow decimals, but not leading 0's.
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSString *myString = [f numberFromString:#"4.5"];
NSLog(#"myString: %#",myString);
NSString *myOtherString = [f numberFromString:#"000"];
NSLog(#"myOtherString:%#",myOtherString);
The output from above would be: 'myString:4.5' and 'myOtherString:0'. I need to be able to do both '4.5' and '000' as output.
I have looked at Apple's "Data Formatting Guide" without much success.
Note that [f numberFromString:#"4.5"] returns an NSNumber* not a NSString*
You want something like this:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
NSNumber *myNumber;
NSString *myString;
myNumber = [f numberFromString:#"4.5"];
[f setNumberStyle:kCFNumberFormatterDecimalStyle];
myString = [f stringFromNumber:myNumber];
NSLog(#"myString: %#",myString);
myNumber = [f numberFromString:#"000"]; // Note that the extra zeros are useless
[f setFormatWidth:3];
[f setPaddingCharacter:#"0"];
myString = [f stringFromNumber:myNumber];
NSLog(#"myString: %#",myString);
NSLog output:
myString: 4.5
myString: 000
If you don't have strings to start with just create number like:
myNumber = [NSNumber numberWithFloat:4.5];
myNumber = [NSNumber numberWithInt:0];
Or just use standard formatting:
myString = [NSString stringWithFormat:#"%.1f", [myNumber floatValue]];
myString = [NSString stringWithFormat:#"%03d", [myNumber intValue]];
Or if you don't need an NSNumber representation just use standard formatting :
myString = [NSString stringWithFormat:#"%.1f", 4.5];
myString = [NSString stringWithFormat:#"%03d", 0];
You could try something like:
NSString *myString = [NSString stringWithFormat:#"%03f", [myNSNumber floatValue]];
This, following the printf format, will print your number forcing at least 3 digits to be printed and padding with '0's any empty space.
How about this as a variation on theme for the 000's
NSNumber *myNumber;
NSString *myString =#"000" ;
NSString * myStringResult;
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterNoStyle;
[f setHasThousandSeparators:FALSE]; //-- remove seperator
[f setMinimumIntegerDigits:[myString length ]]; //-- set minimum number of digits to display using the string length.
myNumber = [f numberFromString:myString];
myStringResult = [f stringFromNumber:myNumber];
NSLog(#"myStringResult: %#",myStringResult);
Since this is asked often and Apple's docs suck, this is the answer that people will be looking for. The link below has two solutions. One using NSString stringWithFormat: and the other using NSNumberFormatter.
https://stackoverflow.com/a/11131497/1058199