Converting an NSArray component into an integer or decimal number - ios

I have a case where the data read from the CSV file in the app has to be converted into an integer, has to be plotted later. Currently it doesn't recognize when the data is saved as
int i=[[rows objectAtIndex:0] componentsSeparatedByString:#","];
This is the implemented code.
-(void)connection :(NSURLConnection *) connection didReceiveData:(NSData *)data{
[self serverConnect];
response = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//NSLog(response);
NSString *stripped1 = [response stringByReplacingOccurrencesOfString:#"\r" withString:#""];
NSArray *rows = [stripped1 componentsSeparatedByString:#"\n"];
NSArray *components;
for (int i=0;i<[rows count]; i++) {
if(i == 0 || [[rows objectAtIndex:i] isEqualToString:#""]){
continue;
}
components = [[rows objectAtIndex:i] componentsSeparatedByString:#","];
NSLog(#"data1:%# data2:%# data3:%#", [components objectAtIndex:0] ,[components objectAtIndex:1],[components objectAtIndex:2]);
}
data1, data2 and data3 are supposed to be integers.
Thanks a lot.

componentsSeparatedByString returns substrings, or instances of NSString.
components = [[rows objectAtIndex:i] componentsSeparatedByString:#","];
You just need to take each member of 'components' and get it's intValue, like so:
int myInt = [[components objectAtIndex:n] intValue];

NSArray and NSMutableArray can only contains objects. So get the integer value from it, use [object intValue]. If you need to add an integer to an array, create a NSNumber object from the integer and insert it. I know Rayfleck answered your question and i just want to point out the way how array works in iOS. Hope this helps.

Related

Fetching separate values from NSDictionary

I have map my data in a NSDictionary. The data is mapped with one key and multiple values.
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
int count = 1;
int intval=111;
int intval2 = 222;
[dict setObject:[NSString stringWithFormat:#"%d,%d",intval,intval2]
forKey#"%d",count];
count++;
How will I fetch both integer value for a key like for key=1? I need to get value 111,222 separately in integer variables.
First thing first you can not addObject(this method is for NSMutableArray) into dictionay, You can setObject or Setvalue for any key.
If you are inserting record same as above and there are two integers separated by comma only than you can get it using below way:
NSString *myBothvalue = [dict valueForKey:#"count"];
NSArray *temp = [myBothvalue componentsSeparatedByString:#","];
NSInteger value1 = [[temp objectAtIndex:0] integerValue];
NSInteger value2 = [[temp objectAtIndex:1] integerValue];
Hope this will help you.
//set object
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
int count = 1; int intval=111; int intval2 = 222;
[dict setObject:[NSString stringWithFormat:#"%d,%d",intval,intval2] forKey:#"count"];
count++;
//Read from dictionary
NSArray *arrayofCount=[[dict valueForKey:#"count"]componentsSeparatedByString:#","];
if(arrayofCount.count>0)
{
int readintval = [[arrayofCount objectAtIndex:0] intValue];
}
if(arrayofCount.count>1)
{
int readintval2 = [[arrayofCount objectAtIndex:1] intValue];
}

how to add total number for NSString

I have a string like
NSString* str = #"[\"40.00\",\"10.00\",\"60.05\"]";
I need the total string amount "110.05"
You can proceed as follows:
1. Make an array out of the string. Since the array is in JSON format, you can do it like this:
NSString* str = #"[\"40.00\",\"10.00\",\"60.05\"]";
NSArray *stringArray = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
2. Convert the strings to double and add them up
double sum = 0;
for (NSString *value in stringArray) {
sum += [value doubleValue];
}
3. Convert the sum back to a NSString:
NSString *sumStr =[[NSString alloc] initWithFormat:#"%f", sum];
Note that approaches that convert NSString to double or float may cause rounding errors, to overcome this issue you must use NSDecimalNumber instead.
How about this?
float myTotal = 0;
for(int i=0;i<[_orderObj.itemArray count];i++) {
NSString *atemp=[_orderObj.itemArray valueForKeyPath:#"price"];
NSLog(#"title %#", atemp);
myTotal = myTotal + [atemp floatValue];
}
NSLog(#"final total==%f", myTotal);

Put multiple arrays in Dictionary

I am parsing a CSV file multiple times with for loop, here I need to store these arrays one by one dictionary. There are very less questions in stack about adding NSArray to NSDictionary. I am parsing CSV with below code but I strucked at storing in NSDictionary, The program is terminating and showing warning at assigning string to dictionary
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serail No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects: keysArray forKeys: string];
}
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSString *key = [NSString stringWithFormat:#"serial%d",i];
[dict setObject:keysArray forKey:key];
}
To get back data from dictionary,
NSArray *array = [dict valueForKey:#"serial24"];//to get array 24.
If I understand you correctly, you want to add the arrays to a dictionary, with the key being the string value of integer i ? What you need to do is allocate the dictionary outside your loop -
NSMutableDictionary *dict=[NSMutableDictionary new];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serial No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
dict[string]=keysArray;
}
I am not sure why you would want to do this, because this is basically an array. You could simply do -
NSMutableArray *outputArray=[NSMutableArray new];
for (NSString *keysString in csvArray) {
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
[outputArray addObject:keysArray];
}

How to sort an Array of signed numbers in iOS?

This may be a simple question, but i don't know the way of doing sorting of array of signed integer values.
My array before sorting,
pointsAry (-2,-7,-5,0,-3,2,-1,-4,1,3,-6)
After using
NSArray * sortedArray = [pointsAry sortedArrayUsingComparator:^(id str1, id str2){
return [(NSString *)str1 compare:(NSString *)str2 options:NSNumericSearch];
}];
Result
sortedArray : (-1,-2,-3,-4,-5,-6,-7,0,1,2,3)
for signed values the sortedArray format is not correct, so i need like
(-7,-6,-5,-4,-3,-2,-1,0,1,2,3)
How to sort like above format ? Thanks in advance.
The following comparator avoids the creation of temporary NSNumber objects:
NSArray *sortedArray = [pointsAry sortedArrayUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
return my_int_compare([str1 intValue], [str2 intValue]);
}];
where
static inline int my_int_compare(int x, int y) { return (x > y) - (x < y); }
is a helper function that compares two integers and returns -1, 0, or +1 (as required
for a comparator method), using the technique from
Is there a standard sign function (signum, sgn) in C/C++?.
Of course the problem only arises because the array contains NSString objects.
Using NSNumbers would be the better solution.
Using the NSNumericSearch option does not help because it does not treat the minus
sign as part of the number.
NSArray *sortedArray = [pointsAry sortedArrayUsingComparator:^(NSString *str1, NSString *str2){
return [#([str1 intValue]) compare:#([str2 intValue])];
}];
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"P3",#"P1",#"P4",#"P10", nil];
NSMutableArray *num=[[NSMutableArray alloc]init];
for(int i=0;i<array.count;i++)
{
NSString *str=array[i];
[num addObject: [str substringFromIndex:1]];
}
NSArray *sortedArray = [num sortedArrayUsingComparator:^(NSString *str1, NSString *str2){
return [#([str1 intValue]) compare:#([str2 intValue])];
}];
[array removeAllObjects];
for(int i=0;i<sortedArray.count;i++)
{
NSString *newString = [NSString stringWithFormat:#"P%#",sortedArray[i]];
[array addObject:newString];
}
It's work for me

How convert string utf-8?

i've an NSString like this:
NSString *word = #"119,111,114,100"
So, what i want to do is to convert this NSString to word
So the question is, in which way can i convert a string to a word?
// I have added some values to your sample input :-)
NSString *word = #"119,111,114,100,32,240,159,145,141";
// Separate components into array:
NSArray *array = [word componentsSeparatedByString:#","];
// Create NSData containing the bytes:
NSMutableData *data = [[NSMutableData alloc] initWithLength:[array count]];
uint8_t *bytes = [data mutableBytes];
for (NSUInteger i = 0; i < [array count]; i++) {
bytes[i] = [array[i] intValue];
}
// Convert to NSString (interpreting the bytes as UTF-8):
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", str);
Output:
word 👍
Try this:
NSString *word = #"119,111,114,100";
NSArray *array=[word componentsSeparatedByString:#","];
for (NSString *string in array) {
char character=[string integerValue];
NSLog(#"%c",character);
}
Output:
w
o
r
d
libicu it's an UTF8 library that supports a conversion from an array of bytes as stated here.
The thing is, it offers Java, C or C++ APIs, not obj-c.

Resources