Can't store all data from NSArray into NSMutableDictionary? [closed] - ios

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
What's the problem with this code?? I am trying to put the data from an NSArray to a NSMutableDictionary but I do not want to first split the initial nsarray into two and then send the data to the nsdcitionary.
The problem is that when I NSLog de mutabledictionary it returns me just the 1 item which happens to be the last data from the NSArray.
NSString *str = #"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:#","];
NSMutableDictionary *dict = [NSMutableDictionary new];
for (int i = 0; i < [arrayFinal count ]; i = i + 2) {
[dict setObject:[arrayFinal objectAtIndex:i] forKey:#"hora"];
[dict setObject:[arrayFinal objectAtIndex:i+1] forKey:#"preco"];
}
The result is:
2013-09-04 20:27:33.732 separa[1438:c07] {
hora = "13:30";
preco = "2.15";
}
Any help will be appreciated.

for (int i = 0; i < [arrayFinal count ]; i = i + 2) {
[dict setObject:[arrayFinal objectAtIndex:i+1] forKey:[arrayFinal objectAtIndex:i]];
}

You need each key to point to an array of values. Something like this:
NSString *str = #"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:#","];
NSMutableArray *horas = [NSMutableArray new];
NSMutableArray *precos = [NSMutableArray new];
for (int i = 0; i < [arrayFinal count]; i += 2) {
[horas addObject:arrayFinal[i]];
[precos addObject:arrayFinal[i + 1]];
}
NSMutableDictionary *dict = [NSMutableDictionary new];
dict[#"hora"] = horas;
dict[#"preco"] = precos;

You're going to need to separate the two (hours and prices) into their own NSMutableArrays, then store each array as one of the keys, something like this:
NSMutableArray *hora = [NSMutableArray alloc] init];
NSMutableArray *preco = [NSMutableArray alloc] init];
NSString *str = #"13:00,2.00,13:05,2.03,13:10,2.07,13:15,2.01,13:20,2.08,13:25,2.10,13:30,2.15";
NSArray *arrayFinal = [str componentsSeparatedByString:#","];
NSMutableDictionary *dict = [NSMutableDictionary alloc] init];
for (int i = 0; i < [arrayFinal count ]; i = i + 2)
{
[hora addObject:[arrayFinal objectAtIndex:i];
[preco addObject:[arrayFinal objectAtIndex:i+1];
}
[dict setObject:hora forKey:#"hora"];
[dict setObject:preco forKey:#"preco"];
Probably not exactly the way I'd do it, but I think it is the concept you're looking for.

Related

Want to reverse some specific word form given string using NSString in ios [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I am new to objective c as well as to iOS.
I have one string like this
NSString *string1 = #"My name is john";
I want to reverse only 'john' to 'nhoj'.
Please Help me!!!.
Thank You
Try This, It will produce your desire output.
NSString *strName = #"My name is john" ;
NSArray *arrStringPart = [strName componentsSeparatedByString:#" "];
NSString *strToReverse = [arrStringPart objectAtIndex:arrStringPart.count - 1];
int len = (int)[strToReverse length];
NSMutableString *mutStrReverce = [[NSMutableString alloc] initWithCapacity:strName.length];
for(int i=0;i<arrStringPart.count-1;i++)
{
[mutStrReverce appendString:[NSString stringWithFormat:#"%# ",[arrStringPart objectAtIndex:i]]];
}
for(int i=len-1;i>=0;i--)
{
[mutStrReverce appendString:[NSString stringWithFormat:#"%c",[strToReverse characterAtIndex:i]]];
}
NSLog(#"%#",mutStrReverce);
Here you go.
May following snippet help you.
NSString *string1 = #"My name is john";
NSArray *arr = [string1 componentsSeparatedByString:#" "];
NSString *temp_sre = [arr objectAtIndex:arr.count - 1];
int len = [temp_sre length];
NSMutableString *reverseName = [[NSMutableString alloc] initWithCapacity:len];
for(int i=len-1;i>=0;i--)
{
[reverseName appendString:[NSString stringWithFormat:#"%c",[temp_sre characterAtIndex:i]]];
}
NSLog(#"reverseName = %#",reverseName);
NSMutableArray *final_array = [[NSMutableArray alloc] init];
final_array = arr.mutableCopy;
[final_array removeLastObject];
[final_array insertObject:reverseName atIndex:final_array.count];
NSString *final_string = [final_array componentsJoinedByString:#" "];
NSLog(#"FInal String = %#",final_string);

How to store values at key =0 into nsarray?

I want to store all the emails into an array. What do I need to do for the same ?
Use this code and change it according to your requirement
NSMutableDictionery * repsonseDict = [[NSMutableDictionery alloc]init];
repsonseDict = [reponseObj objectForKey#"response"];
NSArray * allKeys = [repsonseDict allKeys];
NSMutableArray * emailArr = [[NSMutableArray alloc]init];
for(int i = 0; i < [allKeys count]; i ++ ){
NSString * numberKey = [NSString stringWithFormat:#"%d",i];
[emailArr addObject:[[repsonseDict objectForKey:numberKey]objectForKey:#"email"]];
}

Get substring from string variable and save to NSMutableArray [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am new to iOS development and facing some problem. I have a string like this M||100|??|L||150|??|S||50. I want to break the string into chunks and save to array, e.g M 100 is on 1st index, L 150 on second index, S 50 on third index.
NSString *str = #"M||100|??|L||150|??|S||50";
NSString *stringWithoutBars = [str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[stringWithoutBars componentsSeparatedByString:#"|??|"]];
You can get Array from your string using this code
NSString *str = #"M||100|??|L||150|??|S||50";
str = [str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
NSArray *array = [str componentsSeparatedByString:#"|??|"];
this will return your expected result.
let str = "M||100|??|L||150|??|S||50"
let array = str.componentsSeparatedByString("|??|")
print(array)
result :
["M||100", "L||150", "S||50"]
///First replace "||" with " "
NSString *your_str = #"M||100|??|L||150|??|S||50";
your_str = [your_str stringByReplacingOccurrencesOfString:#"||" withString:#" "];
///Get array of string
NSArray *arr = [your_str componentsSeparatedByString:#"|??|"];
NSMutableArray *data_arr = [[NSMutableArray alloc] init];
for(NSString *str in arr)
{
///string to data conversion
NSData *data = [your_str dataUsingEncoding:NSUTF8StringEncoding];
//////// add data to array
[data_arr addObject: data];
}
NSLog(#"data_arr =%#",data_arr);
NSString *str = #"M||100|??|L||150|??|S||50";
NSArray *arrt = [str componentsSeparatedByString:#"|??|"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
for (int i = 0; i <= arrt.count - 1; i++) {
[arr addObject:[[arrt objectAtIndex:i] componentsSeparatedByString:#"||"]];
}

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

Trying to create an array of dictionaries, keep getting the same dictionary repeated in the array

I'm trying to use NSData to pull information out of a text file, and then load it into a dictionary.
First I create a string of the text file, and load each record into an array.
Then I break apart the each record into individual data elements.
The problem I'm having is that when the dictionary is fully populated, I then use addObject to load it into the array, which it does do successfully. The problem is that when the next loop creates a new dictionary, the same dictionary gets loaded into the array, and I end up an array of all the same dictionaries, instead of multiple different dictionary objects.
I'm guessing there is some simple mistake I'm making that is causing this error. Any help would be appreciated.
NSString *clientListFile = [NSURL URLWithString: #"/textfile"];
NSData *clientListDataFile = [NSData dataWithContentsOfFile:clientListFile];
NSString *clientListString = [[NSString alloc]initWithBytes:[clientListDataFile bytes] length:[clientListDataFile length] encoding:NSUTF8StringEncoding];
NSString *returnDelimiter = #"\n";
NSString *commaDelimiter = #",";
NSString *exclamationDelimiter = #"!";
NSArray *keysAndObjects = [[NSArray alloc]init];
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
NSMutableArray *clientListOfDictionaries = [[NSMutableArray alloc]init];
NSArray *sentenceArray = [clientListString componentsSeparatedByString:returnDelimiter];
for (int i = 0; i < [sentenceArray count]; i=i+1) {
[clientList removeAllObjects]; //to start with a fresh dictionary for the next iteration
NSString *recordSentence = [sentenceArray objectAtIndex:i];
NSArray *attributes = [recordSentence componentsSeparatedByString:commaDelimiter];
for (int j = 0; j < [attributes count]; j = j+1) {
NSString *pairsOfItems = [attributes objectAtIndex:j];
//a small arry, of only two objects, the first is the key, the second is the object
keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
[clientList setObject:[keysAndObjects lastObject] forKey:[keysAndObjects firstObject]];
}
[clientListOfDictionaries addObject:clientList];
}
When I used NSLog to see what's in the dictionary, I mulitple objects of the same dictionary repeated, even though up earlier in the iteration, I can see that the code is creating separate and unique dictionaries.
Instead of this line
[clientListOfDictionaries addObject:clientList];
you can have
[clientListOfDictionaries addObject:[[NSArray alloc] initWithArray:clientList];
That way you will be adding new arrays to clientListOfDictionaries instead of the same one.
Move this line:
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
to just after the first for loop line and then delete the line:
[clientList removeAllObjects];
It's important to create a new dictionary for each iteration.
You should also delete the following line:
NSArray *keysAndObjects = [[NSArray alloc]init];
and change:
keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
to:
NSArray *keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
You are allocated and initialising your clientList dictionary outside of the for loop, so you only have one dictionary, which you are storing in your array multiple times. Adding the dictionary to the array does not copy it, it merely adds a pointer to the object.
you need to move
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
inside your first for loop in place of
[clientList removeAllObjects];
Also, componentsSeparatedByString: returns an NSArray, so you don't need to allocate and initialise one. You can simply define the variable -
NSArray *keysAndObjects;
Because you're using the same clientList variable for each iteration of the loop. You need to create a whole new dictionary object each time.
Try this modified code:
NSData *clientListDataFile = [NSData dataWithContentsOfFile:clientListFile];
NSString *clientListString = [[NSString alloc]initWithBytes:[clientListDataFile bytes] length:[clientListDataFile length] encoding:NSUTF8StringEncoding];
NSString *returnDelimiter = #"\n";
NSString *commaDelimiter = #",";
NSString *exclamationDelimiter = #"!";
NSArray *keysAndObjects = nil;
NSMutableArray *clientListOfDictionaries = [[NSMutableArray alloc] init];
NSArray *sentenceArray = [clientListString componentsSeparatedByString:returnDelimiter];
for (NSUInteger i = 0; i < [sentenceArray count]; ++i) {
NSMutableDictionary *clientList = [[NSMutableDictionary alloc] init]; //to start with a fresh dictionary for the next iteration
NSString *recordSentence = [sentenceArray objectAtIndex:i];
NSArray *attributes = [recordSentence componentsSeparatedByString:commaDelimiter];
for (NSUInteger j = 0; j < [attributes count]; ++j) {
NSString *pairsOfItems = [attributes objectAtIndex:j];
//a small arry, of only two objects, the first is the key, the second is the object
keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
[clientList setObject:[keysAndObjects lastObject] forKey:[keysAndObjects firstObject]];
}
[clientListOfDictionaries addObject:clientList];
}
An alternate option, though likely less efficient, is to to change the line:
[clientListOfDictionaries addObject:clientList];
to
[clientListOfDictionaries addObject:[clientList copy]];
That lets you keep using the same clientList variable, since you're adding a copy of it to the clientListOfDictionaries array. I just point that out because it might help you understand what's going on.
Also, note that I changed this line for you:
NSArray *keysAndObjects = [[NSArray alloc]init];
to
NSArray *keysAndObjects = nil;
Because it's just a pointer that is set by your call to componentsSeparatedByString, you don't need to allocate an array for it. That array will just vanish in your first iteration of the loop.
Should be added the new dictionary to array. Otherwise it will not add to an array. Every object in array have same dictionary mapping. So it will give you the same dictionary value. Create new dictionary for every object and add to array.
for (int i = 0; i < [sentenceArray count]; i=i+1) {
NSMutableDictionary *clientList = [[NSMutableDictionary alloc]init];
NSString *recordSentence = [sentenceArray objectAtIndex:i];
NSArray *attributes = [recordSentence componentsSeparatedByString:commaDelimiter];
for (int j = 0; j < [attributes count]; j = j+1) {
NSString *pairsOfItems = [attributes objectAtIndex:j];
//a small arry, of only two objects, the first is the key, the second is the object
NSArray *keysAndObjects = [pairsOfItems componentsSeparatedByString:exclamationDelimiter];
[clientList setObject:[keysAndObjects lastObject] forKey:[keysAndObjects firstObject]];
}
[clientListOfDictionaries addObject:clientList];
}

Resources