I'm trying to write my NSMutableArray to a text file. I looked at the data with NSLog before I write it, and it's in the format I want
String \t integer \t integer \t integer \r\n
String \t integer \t integer \t integer \r\n
... (50 lines like this)
String \t integer \t integer \t integer \r\n
I write the file by:
[NSKeyedArchiver archiveRootObject:myMutableArray toFile:newPath];
When I look at the file on disk however, it is a bunch of gibberish. Am I doing something wrong here? Or am I understanding how archiveRootObject:toFile: works incorrectly? Thanks.
You can't examine the file directly as it's written in a binary format. You'll have to load it back in order to read it.
See the discussion in the documentation.
Step 1:
if custom objects (say class objects ) are used then
-(id) initWithCoder:(NSCoder *)aDecoder
-(void) encodeWithCoder:(NSCoder *)aCoder
methods in your custom class and have to use NSCoding protocol
Step 2:
in order to retrieve the data from the .bin file
NSFileManager * fm = [NSFileManager defaultManager];
NSURL * docsURL =[fm URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
// this will create the file yourFile.bin if it is not present
NSString * path = [[docsURL path]stringByAppendingString:#"/yourFile.bin"];
self.yourArray = [NSKeyedUnarchiver unarchiveObjectWithFile:self.path];
Step 3:
if you want to save the data on to a .bin file
NSFileManager * fm = [NSFileManager defaultManager];
NSURL * docsURL =[fm URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
this will uses your file if present else it will create it
NSString * path = [[docsURL path]stringByAppendingString:#"/yourFile.bin"];
[NSKeyedArchiver archiveRootObject:self.recordedPlayers toFile:self.path]
that's it, your code should work properly by storing data on to file and retrieve it when you ask for it...
Hope this will solve the problem
As others have noted, the file is written in a binary format.
You can, however examine it - it's a binary plist, so simply naming (or renaming in Finder) to a .plist extensions and opening with Xcode will show you the contents of the keyed archive. The organization of the keys isn't immediately obvious, but if you're looking for a specific value, you can usually find/edit it quite easily:
Related
In my app, I am trying to import the csv files as follow:
NSError *error;
NSString *path1=[[NSString alloc]initWithContentsOfFile:CSVPath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#",path1);
NSArray *messArr=[path1 componentsSeparatedByString:#"\n"];
NSLog(#"%#",messArr);
Question:
When i try to log the array, it gives the last column values with many spaces like as follow:
Path1: student_name,gender,email_id
test1,male,a
test2,male,b
test3,male3,c
messArr:
(
"student_name,gender,email_id
",
"test1,male,a
",
"test2,male,b
",
"test3,male3,c"
)
Here i got the count is 4 but can't able to remove spaces.
So, I can't able to remove spaces from the messArr.
Why this happen? I don't know.
Help me to solve this problem.
i think there is a problem with which encoding scheme you used when you creating the csv file.
Thank you,
Please use CSV Parser available on Github repository.
Use CSV parser for Objective-C
Thanks,
you can remove the spaces
by using this meted on each object of messier
NSString *str=[[messArr objectAtIndex:index] stringByTrimmingCharactersInSet: whitespaceAndNewlineCharacterSet];
use this str for your purpose.
I think it is because of \n. if you dont want it then remove this line
NSArray *messArr=[path1 componentsSeparatedByString:#"\n"];
for showing line iterate your array in for loop, & hardcode the \n in the code
for(int i=0; i<[messArr count];i++)
{
NSLog(#"%#\n",[messArr objectAtindex:i]);
}
I have NSMutableArray like :
NSMutableArray *x=[[NSMutableArray alloc]initWithObjects:#"a",#"b",#"c",#"d", nil];
NSLog(#"%#",x.description);
From the description I got the following result :
(
a,
b,
c,
d
)
I want to again recreate the array from the description is it possible ?
There is no way that would reliably work in all cases. For example, you cannot know if
(
123
)
represents an array containing a string or a number.
Added: There actually is a method to convert the description back to an array object (but it does not always return an identical array for the reason given above). The description method of NSArray and NSDictionary
uses the Old-Style ASCII Property Lists format which can be read using NSPropertyListSerialization:
NSArray *a1 = #[#"123", #456];
NSString *desc = [a1 description];
NSData *d = [desc dataUsingEncoding:NSUTF8StringEncoding];
NSArray *a2 = [NSPropertyListSerialization propertyListWithData:d
options:0
format:NULL
error:NULL];
NSLog(#"%#", a2);
NSLog(#"a1[1] is a %#", [a1[1] class]);
NSLog(#"a2[1] is a %#", [a2[1] class]);
Output:
(
123,
456
)
a1[1] is a __NSCFNumber
a2[1] is a __NSCFString
As you can see, the array a2 looks like a1, but the second element 456, which was a NSNumber originally, has been read back as a NSString.
So you should use description only as a debugging tool. Better methods to create a reversible human-readable description or an archive have been mentioned in the other answers and comments.
While you could, it's not why NSLog() exists. NSLog's purpose is to give a simple error logging mechanism for developers.
You should read into other means of storing data :
Saving to file via NSData.
Using Core Data
NSCoder
Various JSON serializers/parsers.
etc.
But if you really want to, you could parse a log file manually. (With NSRegularExpressions perhaps, NSScanner, etc.)
I am developing an app where users can upload a csv file to documents folder of app (I finished it). But I want to give a textfield to users in the app and ask them to enter a id number and this number will be checked with the uploaded csv files first column. If it matches then display an alert saying that its found a match or else it doesn't.
I believe csv files are text files with comma separated columns and newline (\n) separated rows. So one way to search every row's first column element would be to use NSString's method componentsSeparatedByString:.
EDIT: Load csv file into NSString instance.
NSString * pstrCSVFilePath= [[NSBundle mainBundle] pathForResource:#"CSVFile" ofType:#""]
NSString * pstrCSVFile= [NSString stringWithContentsOfFile:pstrCSVFilePath encoding:NSASCIIStringEncoding error:NULL];
NSArray * paRowsOfCSVFile= [pstrCSVFile componentsSeparatedByString:#"\n"];
NSArray * paColumnsOfRow;
NSString * pstrFirstColumn;
for(NSString * pstrRow in paRowsOfCSVFile)
{
paColumnsOfRow= [pstrRow componentsSeparatedByString:#","];
pstrFirstColumn= [paColumnsOfRow objectAtIndex:0];
if([pstrFirstColumn localizedCaseInsensitiveCompare:myTextField.text] == NSOrderedSame)
{
//Found the search string in the CSV file.
break;
}
}
I want to write all the values present in an array to an excel sheet.Please suggest some way to do so.
Write the values out to a CSV file, import the CSV into Excel.
You have a few options:
Do like #Jonah suggests (I voted for his answer because you had no details!)
Study the XML interchange format from MS Office XML Formats and use NSXML... objects and methods
Depends on what it is you are trying to accomplish
Frank
I will explain writing values out to a CSV file more detail.
For example you have an array of Numbers:
NSArray *array = #[#1,#2, #3,#1.01];
In this case your csv file will looks like this (usual text file with a number on each string):
1
2
3
1.01
So first step is writting a CSV file:
// composing a string with numbers from array separated by "\n" (line-endian symbol)
NSString *string = [array componentsJoinedByString:#"\n"];
// getting data from resulting string
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
// and writting data to disk
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:#"yourFileName.csv"];
[data writeToFile:appFile atomically:YES];
and the last step is to import the CSV into Excel
(just open "yourFileName.csv" with an Excel application and click OK).
But if you want to save array directly in XLS file (without importing into CSV format) you, probably, have to read first answer to this question: iPhone SDK - Export data to XLS (not via CSV)
I'm writing an NSString to a plist file but after its written to the plist, and when I try to open i get the following message
"This document "mylist.plist" could not be opened XML parser error: Unexpected character 2 at line 1 Old-style plist parser error: Unexpected';' or '=' after key at line 1"
Here is my code:
NSString *temp = [NSString stringWithFormat:#"%#\n Selection is %# \n %d for %.2lf = %.2lf", [NSDate date], #"IPC", 2, 42.34, 2 * 42.34];
[temp writeToFile:[self getPathName:#"mylist.plist"] atomically:YES];
any help would be appreciated.
Thanks,
-[NSString writeToFile...] does not create a plist. It creates a text file. There is no such thing as "writing a string to a plist". Only NSArray and NSDictionary objects can be written to plist files. Those can then contain NSString objects (and other objects, like NSDate and NSData, etc), but what you're asking for is not possible.
For more information, check out the Property List Programming Guide.
Edit: I should clarify what I mean by "creating a plist". When I say that, I'm referring to the XML documents defined by the Apple Plist DTD: http://www.apple.com/DTDs/PropertyList-1.0.dtd
%#\n Selection is %# \n %d for %.2lf = %.2lf is definitely not in any plist format. If you want to retain the plist format, use +[NSPropertyListSerialization dataFromPropertyList:...] to convert the string into data as a plist, then save the data.
And I don't see a reason to use plist if you're only storing 1 string. You can simply save as a .txt and load it using +[NSString stringWithContentsOfFile:...].