0

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];
  }
1
  • what is an issue, error? Commented Feb 10, 2015 at 6:39

2 Answers 2

2
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.
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.