Subtracting numbers as Objects - Objective C - ios

I have a sorted array, yrs, which is what it sounds like (a sorted array of years). This array holds 5 objects and each is similar to the object below:
__NSCFNumber * (int)1995 0x79fa3200
I'm trying to subtract the last item from the first item to get the date range:
int first_year = [yrs objectAtIndex:0];
int last_year = [yrs objectAtIndex:4];
NSInteger numberOfCols = ([last_year intValue] - [first_year intValue] ) + 1;
The values of the items in the array are as follows:
first_year int 2078365328 2078365328 where it should be 1995
last_year int 2083083520 2083083520 where it should be
numberOfCols NSInteger 328 328
I honestly have no idea what's going on here.
EDIT
NSMutableArray * years = [NSMutableArray array];
NSMutableArray * atts = [NSMutableArray array];
for(Treatment * treatment in items)
{
NSLog(#"%#",treatment.treatmentMolecule);
NSNumber * startYr = [NSNumber numberWithInt:treatment.startDate.yr];
NSNumber * endYr = [NSNumber numberWithInt:treatment.endDate.yr];
if((![years containsObject:startYr]) && (![startYr isEqual:#0])){
[years addObject:startYr];
}
if((![years containsObject:endYr]) && (![endYr isEqual:#0])){
[years addObject:endYr];
}
}
for(Attack * att in arrayAttack)
{
NSNumber * startYr = [NSNumber numberWithInt:att.yr];
if(![years containsObject:startYr])
[years addObject:startYr];
}
//sort yrs
yrs = [years sortedArrayUsingComparator:(NSComparator)^(NSNumber * yr1, NSNumber * yr2){
return [yr1 compare:yr2];
}];

This is wrong:
int first_year = [yrs objectAtIndex:0];
The element in the array is an instance of NSNumber. Try to replace it with this:
NSNumber *first_year = [yrs objectAtIndex:0];
Even better, you can use firstObject and lastObject instead of hard codes indices.
I would write it like this:
NSNumber *first_year = [yrs firstObject];
NSNumber *last_year = [yrs lastObject];
NSInteger numberOfCols = ([last_year integerValue] - [first_year integerValue] ) + 1;

You should do
int first_year = [[yrs objectAtIndex:0] intValue];
int last_year = [[yrs objectAtIndex:4] intValue];
to get the integer values saved in NSNumber.

Related

How to convert this value into absolute value?

I am getting this from webservice
"rateavg": "2.6111"
now i am getting this in a string.
How to do this that if it is coming 2.6 it will show 3 and if it will come 2.4 or 2.5 it will show 2 ?
How to get this i am not getting. please help me
Try This
float f=2.6;
NSLog(#"%.f",f);
Hope this helps.
I come up with this, a replica of your query:
NSString* str = #"2.611";
double duble = [str floatValue];
NSInteger final = 0;
if (duble > 2.5) {
final = ceil(duble);
}else{
final = floor(duble);
}
NSLog(#"%ld",(long)final);
So it a case of using either ceil or floor methods.
Edit: Since you want it for all doubles:
NSString* str = #"4.6";
double duble = [str floatValue];
NSInteger final = 0;
NSInteger temp = floor(duble);
double remainder = duble - temp;
if (remainder > 0.5) {
final = ceil(duble);
}else{
final = floor(duble);
}
NSLog(#"%ld",(long)final);
check this
float floatVal = 2.6111;
long roundedVal = lroundf(floatVal);
NSLog(#"%ld",roundedVal);
plz use this
lblHours.text =[NSString stringWithFormat:#"%.02f", [yourstrvalue doubleValue]];
update
NSString *a =#"2.67899";
NSString *b =[NSString stringWithFormat:#"%.01f", [a doubleValue]];
// b will contane only one vlue after decimal
NSArray *array = [b componentsSeparatedByString:#"."];
int yourRating;
if ([[array lastObject] integerValue] > 5) {
yourRating = [[array firstObject] intValue]+1;
}
else
{
yourRating = [[array firstObject] intValue];
}
NSLog(#"%d",yourRating);
Try below code I have tested it and work for every digits,
NSString *str = #"2.7";
NSArray *arr = [str componentsSeparatedByString:#"."];
NSString *firstDigit = [arr objectAtIndex:0];
NSString *secondDigit = [arr objectAtIndex:1];
if (secondDigit.length > 1) {
secondDigit = [secondDigit substringFromIndex:1];
}
int secondDigitIntValue = [secondDigit intValue];
int firstDigitIntValue = [firstDigit intValue];
if (secondDigitIntValue > 5) {
firstDigitIntValue = firstDigitIntValue + 1;
}
NSLog(#"final result : %d",firstDigitIntValue);
Or another solution - little bit short
NSString *str1 = #"2.444";
float my = [str1 floatValue];
NSString *resultString = [NSString stringWithFormat:#"%.f",my]; // if want result in string
NSLog(#"%#",resultString);
int resultInInt = [resultString intValue]; //if want result in integer
To round value to the nearest integer use roundf() function of math.
import math.h first:
#import "math.h"
Example,
float ValueToRoundPositive;
ValueToRoundPositive = 8.4;
int RoundedValue = (int)roundf(ValueToRoundPositive); //Output: 8
NSLog(#"roundf(%f) = %d", ValueToRoundPositive, RoundedValue);
float ValueToRoundNegative;
ValueToRoundNegative = -6.49;
int RoundedValueNegative = (int)roundf(ValueToRoundNegative); //Output: -6
NSLog(#"roundf(%f) = %d", ValueToRoundNegative, RoundedValueNegative);
Read doc here for more information:
http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/roundf.3.html
NSString *value = #"1.23456";
float floatvalue = value.floatValue;
int rounded = roundf(floatvalue);
NSLog(#"%d",rounded);
if you what the round with greater value please use ceil(floatvalue)
if you what the round with lesser value please use floor(floatvalue)
You can round off decimal values by using NSNumberFormatter
There are some examples you can go through:
NSNumberFormatter *format = [[NSNumberFormatter alloc] init];
[format setPositiveFormat:#"0.##"];
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.342]]);
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.3]]);
NSLog(#"%#", [format stringFromNumber:[NSNumber numberWithFloat:25.0]]);
Corresponding results:
2010-08-22 15:04:10.614 a.out[6954:903] 25.34
2010-08-22 15:04:10.616 a.out[6954:903] 25.3
2010-08-22 15:04:10.617 a.out[6954:903] 25
NSString* str = #"2.61111111";
double value = [str doubleValue];
2.5 -> 3: int num = value+0.5;
2.6 -> 3: int num = value+0.4;
Set as your need:
double factor = 0.4
if (value < 0) value *= -1;
int num = value+factor;
NSLog(#"%d",num);

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];
}

Deleting the keys and values in NSDictionaries more than the value 100.000 kilometers

I am having a trouble with NSDictionary am adding value as a kilo meters and name as a key this is how am giving
NSDictionary * dd = [NSDictionary dictionaryWithObjects:locationKMArray forKeys:nameArray];
NSLog(#"%#",dd);
This is how outputs looks like
name1 = 1.011115;
name2 = 55.14256;
name3 = 150.48752;
name4 = 22.48668;
:
:
looks like this now i want to print only less than 100.000 kilo meters how can i do this
You can filter the dd as below:
NSSet *keys = [dd keysOfEntriesPassingTest:^BOOL(NSString *key, NSNumber *obj, BOOL *stop) {
return obj.floatValue < 10000;
}];
NSLog(#"%#", keys);
[keys enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
NSLog(#"%#", dd[key]);
}];
NSMutableDictionary *dic = [#{#"name1":#"1.011115 km",#"name2":#"55.14256 km",#"name3":#"150.48752 km",#"name4":#"22.48668 km"}mutableCopy];
for (NSString* key in dic) {
NSString *value = [dic objectForKey:key];
NSArray *array = [value componentsSeparatedByString:#" "];
double km = [[array objectAtIndex:0] doubleValue];
if (km > 100) {
[dic removeObjectForKey:key];
}
}
NSLog(#"%#",dic);
You can do it like this
NSDictionary* dict = [NSDictionary dictionaryWithObjects:locationKMArray forKeys:nameArray];
NSArray*keys=[dict allKeys];
for (NSString* key in keys) {
int km = [dict objectForKey:key];
if (km > 10000) {
NSLog(#"%d" km);
}
}
I don't know if you entered the kms actually with the "km" string or just as ints or longs. Adjust as needed.
Regards

Inputted values from textfield to NSArray

I have a problem creating a solution to this problem:
Create an app that will store 5 numbers (preferrably float) and then sort them out.The array type is immutable.
First off: My problem is how to get the floats from the textfield then put it into a array. My idea is to code it like this:
int a = [num1.text intValue];
int b = [num2.text intValue];
int c = [num3.text intValue];
NSArray *myArray;
myArray = [NSArray stringWithFormat: #"%f",a,b,c];
My second problem is that I can't understand how to sort the floats. Will you please give me some idea?
Thank you very much!
Something like this should work:
CGFloat a = [num1Label.text floatValue];
CGFloat b = [num2Label.text floatValue];
CGFloat c = [num3Label.text floatValue];
CGFloat d = [num4Label.text floatValue];
CGFloat e = [num5Label.text floatValue];
NSArray *array = #[ [NSNumber numberWithFloat:a],
[NSNumber numberWithFloat:b],
[NSNumber numberWithFloat:c],
[NSNumber numberWithFloat:d],
[NSNumber numberWithFloat:e]];
array = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
// logic for sorting
NSNumber *number1 = (NSNumber *)obj1;
NSNumber *number2 = (NSNumber*)obj2;
return [first compare:second];
}];
CGFloat is basically the same as float.
If you check the Documentation (OPTION + Click on that), you see this:
# define CGFLOAT_TYPE float
// ...
typedef CGFLOAT_TYPE CGFloat;
CG comes from Core Graphics.
float comes from C/C++
It is more recommended to use CGFloat in Objective-C, instead of simply float. Also, NSInteger instead of int.

How to add array values in a string in ios

Can anybody please tell me how to put array values[Adding Values] into a string or integer.
Suppose an array a=[1,2,3].
After Adding(+ Action) it should be like
string=1+2+3=>6
Thanks and regards,
Use KVC Collection Operator
NSArray *array =#[#(1),#(2),#(3)];
NSLog(#"Sum is : %#", [array valueForKeyPath:#"#sum.self"]);
Simply loop over your string array and sum it up?!
NSArray *array = #[#"1", #"2", #"3"];
NSInteger sum = 0;
for (NSString *string in array) {
sum += [string integerValue];
}
NSLog(#"%ld", (long)sum);
NSArray *array = #[#1, #2, #3];
int sum = 0;
for (NSNumber * number in array)
{
sum += [number intValue];
}
NSString *result = [NSString stringWithFormat:#"%d", sum];
You can use KVC..
NSNumber *num1 = [NSNumber numberWithInt:1];
NSNumber *num2 = [NSNumber numberWithInt:2];
NSNumber *num3 = [NSNumber numberWithInt:3];
NSArray *arr1= #[num1, num2, num3];
NSString *str = [arr1 valueForKeyPath:#"#sum.intValue"];
NSLog(#"%#",str);
You can use:
NSArray *array = #[#1, #2, #3];
NSInteger sumArray = [[array valueForKeyPath:#"#sum.integerValue"] integerValue];
*I converted the final value to integer, if you don't need then you can replace it by:
NSString *sumArray = [array valueForKeyPath:#"#sum.integerValue"];
It's overkill to use NSArray.
Use plain C array.
int myArray[] = {1,2,3};
int i = 0; int sum= 0;
for (i=0; i < 3; i++){
sum += myArray[i];
}
char str[15];
sprintf(str, "%d", sum);
printf("%s", str);

Resources