Fetching separate values from NSDictionary - ios

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

Related

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

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 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);

How can i check the value from NSDictionary and integer values are same?

i have a dictionary with values as shown in photo,i have integer value of book id . how can i check whether the bookid 's matching or not?
this is my checking codes
NSMutableDictionary *plistdictionary = [[NSMutableDictionary alloc]initWithContentsOfFile:metaDataPath];
NSMutableArray *notes=[plistdictionary objectForKey:#"usernotes"];
NSLog(#"notes value %#",notes);
NSArray *CollectingBookid=[[NSArray alloc]init];
CollectingBookid=[notes valueForKey:#"bookid"];
NSArray *CollectingPages=[[NSArray alloc]init];
CollectingPages=[notes valueForKey:#"pagenumber"];
NSArray *CollectingNotes=[[NSArray alloc]init];
CollectingNotes=[notes valueForKey:#"notes"];
NSLog(#"collection of book id%#",CollectingBookid);
NSString *bookid=#"95";
NSString *page=#"1";
int c=[CollectingBookid count];
for(int i=0;i<c;i++)
{
NSString *singleBookids=[CollectingBookid objectAtIndex:i];
NSString *singlePage=[CollectingPages objectAtIndex:i];
if([singleBookids isEqualToString:bookid])
{
if([singlePage isEqualToString:page])
{
NSMutableArray *CompleteUserNotes=[[NSMutableArray alloc]init];
CompleteUserNotes=[CollectingNotes objectAtIndex:i];
NSLog(#"Selected Notes%#",CompleteUserNotes);
}
}
}
Create a predicate and find the userNote by filtering array
/*As your plist has bookId as string its taken as string.
But if you have bookId as integer before checking
convert it to string for predicate to work*/
NSInteger bookId = 92;
NSString *bookIdString = [NSString stringWithFormat:#"%d",bookId];
NSInteger pageNumber = 12;
NSString *pageNumberString = [NSString stringWithFormat:#"%d",pageNumber];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"bookid == %# AND pagenumber == %#",bookIdString,pageNumberString];
//filteredUserNotes will have all notes matching bookId
NSArray *filteredUserNotes = [notes filteredArrayUsingPredicate:predicate];
//Assuming you only has one entry for bookId and you want a single one
NSDictionary *userNote = [filteredUserNotes lastObject];
Your doing correct comparison by using string formate.
if you want to compare with integer use the below code:
int bookid=95;
int page=1;
int c=[CollectingBookid count];
for(int i=0;i<c;i++)
{
NSString *singleBookids=[CollectingBookid objectAtIndex:i];
NSString *singlePage=[CollectingPages objectAtIndex:i];
if([singleBookids intValue]==bookid)
{
if([singlePage intValue]==page)
{
NSMutableArray *CompleteUserNotes=[[NSMutableArray alloc]init];
CompleteUserNotes=[CollectingNotes objectAtIndex:i];
NSLog(#"Selected Notes%#",CompleteUserNotes);
}
}
}
I'm write this in notepad. Sorry for possible errors.
NSMutableDictionary *plistdictionary = [[NSMutableDictionary alloc]initWithContentsOfFile:metaDataPath];
NSMutableArray *notes=[plistdictionary objectForKey:#"usernotes"];
int bookid = 95;
int page = 1;
for (NSDictionary *collectingObject in notes)
{
int collectingBookid = [[collectingObject objectForKey:#"bookid"] intValue];
int collectingPageid = [[collectingObject objectForKey:#"pagenumber"] intValue];
if (collectingBookid == bookid && collectingPageid == page)
{
NSString *collectingNote = [collectingObject objectForKey:#"notes"];
NSLog(#"Note is: %#", collectingNote);
}
}
You can use this to compare integer value
[singleBookids intValue]==[bookid intValue];

Converting an NSArray component into an integer or decimal number

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.

Resources