IOS: problem to synchronize nsarray with string - ios

I have a NSArray in this way
myArray[0] = [string1, string2, string3, string4, mySecondArray, string5]; (at 0 position)
I write this array inside a txt file in this way
NSString *outputString = #"";
for (int i = 0; i< myArray.count; i++){
outputString = [outputString stringByAppendingString:[[[myArray objectAtIndex:i ] componentsJoinedByString:#"#"] stringByAppendingString:#";"]];
}
NSLog(#"string to write = %#", outputString);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"Text.txt"];
NSError *error;
[outputString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
then the result of NSLog is = (position 0 of myArray) (mySecond array is empty)
one#two#three#four#(
)#five;
I want to know:
Why the array wrap?
When I'll go to read this string how can I know that it's mySecondArray?

When you message componentsJoinedByString: on an NSArray object, it calls description on each of its objects and concatenates them in order. For NSString objects, they are the strings themselves. The array wraps because of the way the description method has been implemented.
As for identifying the array while you are reading the string back, I don't think it is possible. You should consider writing the array to the file rather i.e.
[[myArray objectAtIndex:0] writeToFile:filePath atomically:YES];
or
[myArray writeToFile:filePath atomically:YES];
depending on the requirement. This way you will be able to read the elements back properly.

Related

Trying to load a saved NSMutableArray

This is the code I'm using to save an NSMutableArray "names" (after the user presses a save button), and I think it's working without problems, but I'm not sure what the corresponding code would be to then load my array when I reopen my app. Any help would be greatly appreciated!
- (IBAction)save:(id)sender {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullFileName = [NSString stringWithFormat:#"%#/temporaryArray", docDir];
[NSKeyedArchiver archiveRootObject:names toFile:fullFileName];
}
Well, you're halfway there. You've figured out how to archive the object. The question is, how do you unarchive it? As I explained in my comment, this is done with the very aptly named NSKeyedUnarchiver class.
Let's begin with a code sample:
#try {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *defaultPath = [docDir stringByAppendingPathComponent:#"temporaryArray"];.
self.yourArray = [NSKeyedUnarchiver unarchiveObjectWithFile: defaultPath];
if (!self.yourArray) {
NSLog(#"Error!");
} else {
// Success!
}
} #catch (NSException *exception) {
NSLog(#"Some error happened: %#", exception);
}
The NSKeyedUnarchiver class takes a path to a file containing the content archived by NSKeyedArchiver. It will then read this file and return the "root" object -- the object that you told NSKeyedArchiver to archive. It's that simple. (You should, of course, include error handling, which I gave a brief example of above.)
If you want another resource, you can read this great introductory article by the famous Mattt Thompson, which gives a good explanation of the concepts behind the class.
Hope this helps.
If your array's contents are all property list objects (NSString, NSData, NSArray, or NSDictionary objects) then you can do saving and reading in a way other than using NSKeyedArchiever/NSKeyedUnarchiever:
- (IBAction)save:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullFileName = [docDir stringByAppendingPathComponent:#"temporaryArray"];
[names writeToFile:fullFileName atomically:YES];
}
- (NSMutableArray*)readNames
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullFileName = [docDir stringByAppendingPathComponent:#"temporaryArray"];
return [NSMutableArray arrayWithContentsOfFile:fullFileName];
}
- (IBAction)save:(id)sender
{
// check for previous data persistancy.
NSArray *arrData = [[NSUserDefaults standardDefaults]objectforkey:#"Paths"];
if(arrData == nil)
{
// Maintain your old data and update it in new one to store the same.
NSMutableArray *arrTempData = [NSMutableArray arrayWithArray:arrData];
//Add Some data to old array based on your bussiness logic.
[arrTempData add object:#"some data"];
// Update in User Defaults
[[NSUserDefaults standardDefaults]setobject:[NSArray arrayWithArray:arrTempData] forkey:#"Paths"];
}
}
Somewhere in your code,put below code to get the data,
NSArray *arrSavedData = [[NSUserDefaults standardDefaults] objectforkey:#"Paths"];

View Image array from web folder in iOS

I want to be able to view images from a web folder inside my iPhone app. I know how to view the images with a specific url (i.e. www.mywebsite.com/image.jpg). That's easy. I just don't know how to asynchronously load an array. Basically I need to view images with a specific sequence (i.e. mywebsite.com/image_001.jpg, image_002.jpg, image_003.jpg, etc). There may be 10 or 100 images in a folder with that sequence. How do I let my app load images with a sequence?
Following code will sort images of this file format "imageName_number.jpg"
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *webDir=[documentsDirectory stringByAppendingPathComponent:#"WebFolder"];
NSFileManager *filemgr;
NSMutableArray *fileNum;
fileNum=[[NSMutableArray alloc]init];
filemgr = [NSFileManager defaultManager];
//This will give all files of your web directory you can uncomment to get dynamically
//NSArray *filelist = [filemgr contentsOfDirectoryAtPath: webDir error: nil];
// this is just example shows how unsorted will be used to sort image no you can comment this line
NSArray *filelist=[[NSArray alloc]initWithObjects:#"abc_001.jpg",#"def_005.jpg",#"abc_002.jpg",#"abc_0103.jpg",#"abc_0010.jpg",#"abc_008.jpg", nil];
int count = (int)[filelist count];
NSMutableDictionary *dictFileNumWithPath=[[NSMutableDictionary alloc]init];
NSString *imageSeprator=#"_";
for (int i = 0; i < count; i++){
NSString *imageName=[filelist objectAtIndex: i];
if (!([imageName rangeOfString:imageSeprator].location == NSNotFound)) {
NSRange startRange = [imageName rangeOfString:imageSeprator];
NSRange endRange = [imageName rangeOfString:#".jpg"];
NSRange searchRange = NSMakeRange( startRange.location+1, endRange.location-endRange.length);
NSString *strNum= [imageName substringWithRange:searchRange];
NSString *webPath=[webDir stringByAppendingPathComponent:imageName];
[dictFileNumWithPath setObject:[NSNumber numberWithInt:[strNum intValue]] forKey:webPath];
}
}
NSArray *sortedKeysFilePathArray =
[dictFileNumWithPath keysSortedByValueUsingSelector:#selector(compare:)];
NSLog(#"%#", sortedKeysFilePathArray);

How to write array data into excel file (CSV) in objective c

I am trying to write the array data into excel (actually it is a CSV, but it is opened in excel). I used the following code to do that:
NSMutableArray *list;
list = [[NSMutableArray alloc] init];
NSString *string = [list componentsJoinedByString:#","];
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"yourFileName.csv"];
[data writeToFile:appFile atomically:YES];
It works fine, but the problem is I have 20 objects in my 'list' array and all those 20 objects are written in side by side cells. What I want is to write the first 4 objects in one line and then move to the new line and again write the next 4 objects in that line till all the objects in the list array are completed.
Can anyone help me with this issue?
NSMutableArray *list = ...
NSMutableString *buffer = [NSMutableString string];
for (NSUInteger i = 0; i < list.count; i++) {
NSString *value = list[i];
if (i > 0) {
if (i % 4 == 0) { //after every 4th value
buffer.append("\n"); //end line
}
else {
buffer.append(",");
}
}
buffer.append(value);
//if your values contain spaces, you should add quotes around values...
//buffer.appendFormat(#"\"%#\"", value);
}
NSData *data = [buffer dataUsingEncoding:NSUTF8StringEncoding];
...
To break lines in CSV just input a \r\n in the "end of the line". Be caerfull because in the mac you only need \r or \n (not really sure right now)

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 ... ?

How to write a String in different lines to a .txt file on iOS

I am trying to write a string to a t.t file in the documents folder of my app. I can write the string to it, but when I write another string to the file it overwrites the other string, is it possible to write more strings to a text files, with a blank line between strings, many in this formate
String
String
Strine
…
I am using this code to write the string to an text file, it works for one string, but not for multible strings.
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/Barcodedata.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = [NSString stringWithFormat:#"%#",sym.data];
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:nil];
There's a few ways to do this, depending on how you implemented your code.
One way would be to load up the original .txt file into a NSMutableString object and then append that new line to the end of the string and re-write out the file (this isn't super efficient, especially as you start appending after 1000 strings, 100 strings, 50 strings, etc.)
Or you could use the low level C function "fwrite" with the append bit set.
Edited:
Since you want to see code, here's how to do it with my first suggestion:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:#"%#/Barcodedata.txt", documentsDirectory];
//create content - four lines of text
NSError * error = NULL;
NSStringEncoding encoding;
NSMutableString * content = [[NSMutableString alloc] initWithContentsOfFile: fileName usedEncoding: &encoding error: &error];
if(content == NULL)
{
// if the file doesn't exist yet, we create a mutable string
content = [[NSMutableString alloc] init];
}
if(content)
{
[content appendFormat: #"%#", sym.data];
//save content to the documents directory
BOOL success = [content writeToFile:fileName
atomically:NO
encoding:NSStringEncodingConversionAllowLossy
error:&error];
if(success == NO)
{
NSLog( #"couldn't write out file to %#, error is %#", fileName, [error localizedDescription]);
}
}

Resources