IOS: problem with nsarray layout - ios

In this code I read a file txt: this txt file have information in this way:
one#two#three#four#five;one#two#three#four#five;
- (void) readFile{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"File.txt"];
NSString *fileString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
if (!fileString) {
NSLog(#"Error reading file.");
}
NSMutableArray *itemDB = [[fileString componentsSeparatedByString:#";"] mutableCopy];
[itemDB removeLastObject];
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
for (int i = 0; i<[itemDB count]; i++) {
NSArray *datiItemDB = [[itemDB objectAtIndex:i] componentsSeparatedByString:#"#"];
[returnArray addObject: datiItemDB];
}
one = [[NSMutableArray alloc] initWithArray:(NSArray*)returnArray];
[returnArray release];
}
the result of nslog of this array is
2011-07-04 10:01:16.847 Project[254:707] array one:(
(
"(\n 0,\n 1,\n 12,\n \"2011-07-04 08:00:41 +0000\",\n \"2011-07-15 00:00:00 +0000\",\n \"\",\n 0,\n 0,\n (\n ),\n \"\"\n)"
)
)
but I want that the result of nslog is
2011-07-04 09:52:07.281 Project[230:707] array one:(
(
0,
1,
1,
"2011-07-04 07:45:15 +0000",
"2011-07-04 07:45:15 +0000",
"",
0,
0,
(
),
""
)
)
Why I have "/n" symbols, and how can I remove it from my array?

Do you just want to put the first part of the text file in an array? I think you are overcomplicating the problem. What about something like this:
NSString *inputString = #"one#two#three#four#five;one1#two2#three3#four4#five5;";
NSArray *arrayFromInputString = [inputString componentsSeparatedByString:#";"];
NSArray *component1 = [[arrayFromInputString objectAtIndex:0] componentsSeparatedByString:#"#"];
NSLog(#"1: %#", [component1 description]);
NSArray *component2 = [[arrayFromInputString objectAtIndex:1] componentsSeparatedByString:#"#"];
NSLog(#"2: %#", [component2 description]);
If you run that, the output is
[777:207] 1: (
one,
two,
three,
four,
five
)
[777:207] 2: (
one1,
two2,
three3,
four4,
five5
)
Is this what you wanted? If not, can you try to explain better?

Related

NSDictionary in NSMutableArray ios

I've a NSMutableArray array having NSDictionary keys as:
NSMutableArray *arr=#[#{#"A":#{#"user":#"obj1",#"friend":#"obj2"}}];
No I want to add objects to this NSMutableArray.
My Code:
for (int i = 0; i < 10; i++)
{
NSString *user = #"A"+i;
for(int i=0;i<50;i++) {
NSString *friend1 = #"B"+i;
NSString *friend2 = #"C"+i;
NSString *friend3 = #"D"+i;
}
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
NSString *y= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",y);
Desired Output:
{"A":[{"user":"A1","friend":"B1"},{"user":"A1","friend":"B2"},{"user":"A2","friend":"B1"}]}
How can I set my objects in order to achieve desired output.
NSString* singleObjectTemplate = [NSString stringWithFormat:#"{\"user\" : \"%#\",\"friend\" : \"%#\"}", user, friend];
NSString* validJsonTemplate = [NSString stringWithFormat:#"{\"A\":[%#]}", singleObjectTemplate];
Something like this. You can modify it as per your requirement to add multiple entries.
I hope this helps you in some way. Cheers!! :)
EDIT:
Suppose you want to add 3 objects to it.
NSString *str = #"";
for (int i = 0; i<3; i++)
{
NSString* singleObjectTemplate = [NSString stringWithFormat:#"{\"user\" : \"%#\",\"friend\" : \"%#\"}", user, friend];
str = [str stringByAppendingString:singleObjectTemplate];
if(i<2)
str = [str stringByAppendingString:#", "];
}
NSString* validJsonTemplate = [NSString stringWithFormat:#"{\"A\":[%#]}", str];

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

Data in csv file after export

I have a problem with data who are exported to a csv file.
It concerns the data with accented characters. Type Data is string.
in my file i have this :
Téléphones et internet; Abonnement iPad; 13,90 €; Débit
I would like to have :
Téléphones et internet; Abonnement iPad; 13,90€ Débit
what code should be used to do this?
Thank you.
EDIT : my code
NSMutableString *writeString = [NSMutableString string];
for (id object in [[self fetchedResultsController] fetchedObjects]) {
NSString * object1 = [[object valueForKey:#"object1Data"] description];
NSString * object2 = [[object valueForKey:#"object2Data"] description];
NSString * object3 = [[object valueForKey:#"object3Data"] description];
NSString * object4 = [[object valueForKey:#"object4Data"] description];;
[writeString appendString:[NSString stringWithFormat:#"%#; %#; %#; %#\n", object1, object2, object3, object4]];
}
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* savePath = [paths objectAtIndex:0];
savePath = [savePath stringByAppendingPathComponent:#"objectData.csv"];
[writeString writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
EDIT2 : for viewing i use his :
QLPreviewController *previewController=[[QLPreviewController alloc]init];
previewController.delegate=self;
previewController.dataSource=self;
[self presentViewController:previewController animated:YES completion:nil];
[previewController.navigationItem setRightBarButtonItem:nil];
- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* savePath = [paths objectAtIndex:0];
savePath = [savePath stringByAppendingPathComponent:#"objectData.csv"];
return [NSURL fileURLWithPath:savePath];
}
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
return 1;
}
Your output looks like it might be correct, the problem seems like it’s in how you are viewing it.
Are you importing it into Excel or something? Excel’s CSV import is very poor in my experience, and it won’t auto-detect incoming UTF-8 data.
It's likely the encoding that's causing an issue here.
As a side note it's a CSV = Comma Separated Values. You aren't putting the commas in .. ?
Change:
[writeString appendString:[NSString stringWithFormat:#"%#; %#; %#; %#\n", object1, object2, object3, object4]];
To:
[writeString appendString:[NSString stringWithFormat:#"%#;, %#;, %#;, %#\n", object1, object2, object3, object4]];
This will make the values appear in separate columns when opened in excel, unless you want it all in 1 column ... ?

Create a Custom Formatted Dictionary Array from CSV File of Data

I've created an iPhone app that has a dictionary array of locations (lat,long,point). I created the array by manually entering each value.
myLocationArray = #[
#{
kStation : #"1",
kLatitude : #( 41.656467),
kLongitude : #(-81.277963)
},
#{
kStation : #"2",
kLatitude : #(41.657118),
kLongitude : #(-81.276545)
},
#{
kStation : #"3",
kLatitude : #(41.658493),
kLongitude : #(-81.273542)
},
...
This is good and works but now I want to create this array programmatically by getting the data from a .CSV file. I have a .CSV file (TestCSV.csv) that looks like this.
41.656467,-81.277963,27200
41.657118,-81.276545,27650
41.658493,-81.273542,28631.5
41.660728,-81.268547,30195
41.661830,-81.266065,30991
41.662828,-81.263819,31700
41.663677,-81.261962,32300
41.664578,-81.259909,32950
41.666210,-81.256312,34100
41.666921,-81.254708,34605
41.668043,-81.252191,35400
41.669044,-81.250043,36099
41.670120,-81.247495,36900
41.670778,-81.245957,37380
41.671459,-81.244292,37905
41.672028,-81.242832,38349
41.672487,-81.241702,38700
41.673106,-81.240175,39175
41.674364,-81.237007,40150
41.675170,-81.235038,40762.5
41.675716,-81.233698,41182
41.676143,-81.232614,41516
Specifically, I'd like to create myLocationArray (with formatting as shown) by reading straight from the TestCSV.csv. I'm not familiar with the code to achieve this and would really appreciate some direction.
Also, would it be any different or easier if the data was provided via text file instead of csv?
Try
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Locations" ofType:#"csv"];
NSString *csvString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *locations = [csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *locationsArray = [NSMutableArray array];
for (NSString * location in locations)
{
NSArray *components = [location componentsSeparatedByString:#","];
double latitude = [components[0] doubleValue];
double longitude = [components[1] doubleValue];
NSString *station = components[2];
NSDictionary *dict = #{#"kLatitude": #(latitude),
#"kLongitude": #(longitude),
#"kStation": station};
[locationsArray addObject:dict];
}
CSV File
Answer inspired from
csv file IS a plain-text file. To achive what you want you can use NSScanner and NSString componentsSeparatedByString: Everything else is really simple.
Answer provided by Anupdas. Cheers!
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Locations" ofType:#"csv"];
NSString *csvString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSArray *locations = [csvString componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *locationsArray = [NSMutableArray array];
for (NSString * location in locations)
{
NSArray *components = [location componentsSeparatedByString:#","];
double latitude = [components[0] doubleValue];
double longitude = [components[1] doubleValue];
NSString *station = components[2];
NSDictionary *dict = #{#"kLatitude": #(latitude),
#"kLongitude": #(longitude),
#"kStation": station};
[locationsArray addObject:dict];
}

Plist dicionaries keys

I am using this code to add content into a plist :
//////////// Save data into plist /////////////////
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"datatesting.plist"];
NSLog(#"path='%#'",path);
NSFileManager *nfm = [[NSFileManager alloc] init];
if([nfm fileExistsAtPath:path])
{
// if file exists, get its contents, add more entries and write back
NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
NSArray *keys = [NSArray arrayWithObjects:#"Title",#"Description",#"Coordinate",nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:#"%#",titlestring],[NSString stringWithFormat:#"%#",descriptionstring],[NSString stringWithFormat:#"%#",coordinadastring], nil] forKeys:keys]];
NSLog(#"modified array=%#",array);
BOOL ok = [array writeToFile:path atomically:YES];
if(!ok){
NSLog(#"Unable to write appended file");
return;
}
} else {
// if file doesn't exist, create a new one
NSMutableArray *array = [[NSMutableArray alloc] init];
NSArray *keys = [NSArray arrayWithObjects:#"Title",#"Description",#"Coordinate",nil];
[array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:#"%#",titlestring],[NSString stringWithFormat:#"%#",descriptionstring],[NSString stringWithFormat:#"%#",coordinadastring], nil] forKeys:keys]];
NSLog(#"new array=%#",array);
BOOL ok = [array writeToFile:path atomically:YES];
if(!ok){
NSLog(#"Unable to write new file");
return;
}
}
Now I am having issues in using the content of the plist. So my two questions are :
- What is the Keys of the dictionaries of the current plist ?
- What is the way to read the content in a Tableview ?
You have an array of dictionaries. You need to iterate on the contents of the array, then look at each dictionary. You can do this with block enumerators or the older for() style. I'll use the latter now as you may not know blocks.
NSArray *array = ...; // read in the array from the file
for(NSDictionary *dict in array) {
NSString *title = [dict objectForKey:#"Title"];
... etc
}
When you want to show this data in a tablview, the number of rows is the number of dictionaries (ie [array count]). If you wanted to show just the title for each cell, you would get the cell row number, then get the dictionary by [array objectAtIndex:cellRow]), then pull out the title as above.

Resources