writing NSString type to a file - iphone

I'm implementing the following function on appdelegate,
but I need to write NSString type instead of typical float values.
Since xcode doesn't allow an object to be in my desired position,
I used char* instead as follows, where as my data to be passed are of type NSString.
As expected, it doesn't work...
How could I manipulate it so that I could write NSString data type?
Should I make some conversion?
Please help me out..
- (void)addHallOfFamer:(char*)newHofer{
[hofArray addObject:[NSString stringWithFormat:#"%#",newHofer]];
[hofArray sortUsingSelector:#selector(compare:)];
NSArray* paths =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* hofArrayPath = [documentsDirectory
stringByAppendingPathComponent:#"hofers.plist"];
[hofArray writeToFile:hofArrayPath atomically:YES];
}
(added)
following is how I'm calling the written NSStrings from another view, which doesn't reflect my updating.
MainAppDelegate* delegate;
delegate = (MainAppDelegate*)[[UIApplication sharedApplication] delegate];
NSArray *hofers = [[delegate.hofArray reverseObjectEnumerator] allObjects];
hoferName1.text = [NSString stringWithFormat:#"%#",[hofers objectAtIndex:0]];

First, with the current char * argument, you need to use %s as your format directive, not %#.
Second, to use an NSString * as your argument, just add it to hofArray.

The easiest solution would be to just save the array in NSUserDefaults. Since it is an array of strings, saving and retrieving it that way should work fine and would be easier than dealing with the iOS filesystem.
Edit:
If you really want to save it in the filesystem, look into the NSKeyedArchiver method + (BOOL)archiveRootObject:(id)rootObject toFile:(NSString *)path and the NSKeyedUnarchiver method + (id)unarchiveObjectWithFile:(NSString *)path.
Edit 2:
As ondmike pointed out, you need to use %s rather than %# for your -stringWithFormat: method call to work properly. Relevant documentation is String Format Specifiers

Related

How to selectively trim an NSMutableString?

I would like to know how to selectively trim an NSMutableString. For example, if my string is "MobileSafari_2011-09-10-155814_Jareds-iPhone.plist", how would I programatically trim off everything except the word "MobileSafari"?
Note : Given the term programatically above, I expect the solution to work even if the word "MobileSafari" is changed to "Youtube" for example, or the word "Jared's-iPhone" is changed to "Angela's-iPhone".
Any help is very much appreciated!
Given that you always need to extract the character upto the first underscore; use the following method;
NSArray *stringParts = [yourString componentsSeparatedByString:#"_"];
The first object in the array would be the extracted part you need I would think.
TESTED CODE: 100% WORKS
NSString *inputString=#"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *array= [inputString componentsSeparatedByString:#"_"];
if ([array count]>0) {
NSString *resultedString=[array objectAtIndex:0];
NSLog(#" resultedString IS - %#",resultedString);
}
OUTPUT:
resultedString IS - MobileSafari
If you know the format of the string is always like that, it can be easy.
Just use NSString's componentsSeparatedByString: documented here.
In your case you could do this:
NSString *source = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *seperatedSubStrings = [source componentsSeparatedByString:#"_"];
NSString *result = [seperatedSubStrings objectAtIndex:0];
#"MobileSafari" would be at index 0, #"2011-09-10-155814" at index 1, and #"Jareds-iPhone.plist" and at index 2.
Try this :
NSString *strComplete = #"MobileSafari_2011-09-10-155814_Jareds-iPhone.plist";
NSArray *arr = [strComplete componentsSeparatedByString:#"_"];
NSString *str1 = [arr objectAtIndex:0];
NSString *str2 = [arr objectAtIndex:1];
NSString *str3 = [arr objectAtIndex:2];
str1 is the required string.
Even if you change MobileSafari to youtube it will work.
So you'll need an NSString variable that'll hold the beginning of the string you want to truncate. After that one way could be to change the string and the variable string values at the simultanously. Say, teh Variable string was "Youtube" not it is changed to "MobileSafari" then the mutable string string should change from "MobileSafari_....." to "YouTube_......". And then you can get the variable strings length and used the following code to truncate the the mutable string.
NSString *beginningOfTheStr;
.....
theMutableStr=[theMutableStr substringToIndex:[beginningOfTheStrlength-1]];
See if tis works for you.

Writing an array of NSData to file

I am trying to save an array of images to the documents folder. I managed to save an image as NSData and retrieve it using the method below, but saving an array seems to be beyond me. I've looked at several other questions that relate and it seems I'm doing everything right.
Adding the image as NSData and saving the image:
[imgsData addObject:UIImageJPEGRepresentation(img, 1.0)];
[imgsData writeToFile:dataFilePath atomically:YES];
Retrieving the data:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"imgs.dat"];
[self setDataFilePath:path];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:dataFilePath])
imgsData = [[NSMutableArray alloc] initWithContentsOfFile:dataFilePath];
So, writing an image as NSData using the above works, but not an array of images as NSData. It inits the array, but it has 0 objects, which isn't correct, since the array I am saving has several. Does anyone have any ideas?
First of all, you should brush up Cocoa Memory Management, the first line of code is a little bit of a worry.
For data serialisation, you may like to have a go with NSPropertyListSerialization. This class serialises arrays, dictionaries, strings, dates, numbers and data objects. It has an error reporting system, unlike the initWithContentsOfFile: methods. The method names and arguments are a bit long to fit on one line, so sometimes you may see them written with Eastern Polish Christmas Tree notation. To save your imgsData object, you can use:
NSString *errString;
NSData *serialized =
[NSPropertyListSerialization dataFromPropertyList:imgsData
format:NSPropertyListBinaryFormat_v1_0
errorDescription:&errString];
[serialized writeToFile:dataFilePath atomically:YES];
if (errString)
{
NSLog(#"%#" errString);
[errString release]; // exception to the rules
}
To read it back in, use
NSString *errString;
NSData *serialized = [NSData dataWithContentsOfFile:dataFilePath];
// we provide NULL for format because we really don't care what format it is.
// or, if you do, provide the address of an NSPropertyListFormat type.
imgsData =
[NSPropertyListSerialization propertyListFromData:serialized
mutabilityOption:NSPropertyListMutableContainers
format:NULL
errorDescription:&errString];
if (errString)
{
NSLog(#"%#" errString);
[errString release]; // exception to the rules
}
Check the contents of errString to determine what went wrong. Keep in mind that these two methods are being deprecated in favour of the dataWithPropertyList:format:options:error: and propertyListWithData:options:format:error: methods, but these were added in Mac OS X 10.6 (I'm not sure if they're available on iOS).

Array of Arrays - writing to File problem

and again my array of arrays ... I try to improve my app performance by buffering arrays on file for later reuse.
I have an NSMutableArray that contains about 30 NSMutableArrays with NSNumber, NSDate and NSString Objects.
I try to write the file using this call:
bool result = [myArray writeToFile:[fileMethods
getFullPath:[NSString
stringWithFormat:#"iEts%#.arr",
[aDate shortDateString]]]
atomically:NO];
=> result = FALSE.
The Path method is:
+ (NSString *) getFullPath:(NSString *)forFileName {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:forFileName];
}
and the aDate call returns a shortDateString with ddMMyy.
The NSLog
NSLog(#"%#", [fileMethods getFullPath:[NSString stringWithFormat:#"iEts%#.arr",
[aDate shortDateString]]]);
on the path generation returns:
/Users/me/Library/Application Support/iPhone Simulator/User/Applications/86729620-EC1D-4C10-A799-0C638BB27933/Documents/iEts010510.arr
FURTHER:
It must have something to do with the
Array of Arrays, since I also write 3
further simple arrays (containing
NSStrings) that all succeed.
The Array of Arrays gets generated using the addObject method
Any ideas what could cause the trouble?
AFAIK the write to file uses object archiving hence some objects in your array of arrays can't be archived.
Have you got any NSNulls in your arrays anywhere? I don't think they count as plist objects and so would cause the write to fail.

iPhone SDK: How do I properly save user-inputted information into a .plist or other file?

I've looked through the SDK documentation and through other questions that have been asked, and I am still a little confused on how exactly to do this. I had been previously been working with the following code, though it does not give the desired result of a .plist file. Besides mentioning the IBAction in the header files in this code in the .m file, is there anything else that needs to be added or anothe method I should be taking? Thanks!
My Code:
- (IBAction)fedDog {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"dogsFedDays.plist"];
NSMutableArray *dogsFedSave = [NSMutableArray arrayWithCapacity: 100];
for (int i = 0; i < 100; i++) {
NSDictionary *myDict = [[NSDictionary alloc] initWithObjectsAndKeys:
date[i], #"string",
fed[i], #"Yes",
nil];
[dogsFedSave addObject:myDict];
[myDict release];
}
if (![dogsFedSave writeToFile:path atomically:YES])
NSLog(#"not successful in completing this task");
}
I'm assuming that -writeToFile is returning NO so you're seeing your NSLog statement (correct me if I'm wrong). If that's the case, then the issue must be that some object in either your date array, or fed array is not any of the allowed object types for property lists which includes: NSString, NSData, NSArray, or NSDictionary. NSNulls are not allowed. From the docs for writeToFile:
This method recursively validates that
all the contained objects are property
list objects before writing out the
file, and returns NO if all the
objects are not property list objects,
since the resultant file would not be
a valid property list.

Plist not saving from dictionary (to Documents)

I've been trying to save a plist of a NSDictionary to my app's Documents folder. I haven't tried this on the device yet but I'd like it to work on the simulator for testing purposes. The [self createDictionaryFromChoreList] method just creates a NSDictionary from some data in another class of mine. I've pretty much copied/pasted this code from the web documents and when I go to see if the file was saved or not, I find that it isn't. Here is the method block.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *plistName = [[NSString alloc] initWithFormat:#"%#chores.plist", self.firstName];
NSString *path = [documentsDirectory stringByAppendingPathComponent:plistName];
NSDictionary *choresDictionary = [[NSDictionary alloc] initWithDictionary:[self createDictionaryFromChoreList]];
[choresDictionary writeToFile:path atomically:YES];
Any help is greatly appreciated. Thanks in advance.
-S
You should also capture the BOOL returned by writeToFile:atomically:. That will tell you if the write succeeded or not.
Also, are you sure you are looking in the right documents folder? If you have more than one app in the simulator its easy to open the wrong app's documents folder in the Finder. I did that once and it cost me a couple of hours of frustration.
Edit01:
writeToFile:atomically: returning false explains why no file exist. The simplest explanation is that something in the dictionary is not a property list object.
From the NSDictionary docs:
This method recursively validates that
all the contained objects are property
list objects (instances of NSData,
NSDate, NSNumber, NSString, NSArray,
or NSDictionary) before writing out
the file, and returns NO if all the
objects are not property list objects,
since the resultant file would not be
a valid property list.
It just takes one non-plist object buried deep in a dictionary to prevent it from being converted to a plist.
Don't forget serialize the plist data:
Here is a snippet of code that I use for writing information to a plist
NSString *errorString;
NSData *data = [NSPropertyListSerialization dataFromPropertyList:plistDict
format:NSPropertyListXMLFormat_v1_0
errorDescription:&errorString];
[plistDict release];
if (!data) {
NSLog(#"error converting data: %#", errorString);
return NO;
}
if ([data writeToFile:[XEraseAppDelegate loadSessionPlist] atomically: YES]) {
return YES;
} else {
NSLog(#"couldn't write to new plist");
return NO;
}
This is something I whipped up really quickly and it correctly writes a plist directory of name and company to the documents directory. I have a feeling your dictionary creation method might have an issue. Try this out for yourself, then add your code and make sure it works.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistDirectory = [paths objectAtIndex:0];
NSString *plistPath = [plistDirectory stringByAppendingPathComponent:#"userCompany.plist"];
NSArray *userObjects = [[NSArray alloc] initWithObjects:#"Joe", #"Smith", #"Smith Co", nil];
NSArray *userKeys = [[NSArray alloc] initWithObjects:#"First Name", #"Last Name", #"Company", nil];
NSDictionary *userSettings = [[NSDictionary alloc] initWithObjects:userObjects forKeys:userKeys];
[userSettings writeToFile:plistPath atomically:YES];
Is it correct, that the name of file your writing to is:
SOEMTHINGchores.plist?
Created via:
NSString *plistName = [[NSString alloc] initWithFormat:#"%#chores.plist", self.firstName];
Also, what is the output of:
[choresDictionary print];
Some additional info would help to debug this.
Where exactly are you looking for the file?
I have the exact same code and it works fine for me.
Just that I have to dig deep to get the file. Something like:
/Users/myUserName/Library/Application Support/iPhone Simulator/User/Applications/0E62A607-8EEB-4970-B198-81CE4BDDB7AA/Documents/data.plist
And the HEX number in the path changes with every run. So I print the file path with every run.
Insert a break point at
NSDictionary *choresDictionary = [[NSDictionary alloc] initWithDictionary:[self createDictionaryFromChoreList]];
now when you step out drag your mouse over choresDictionary and check in the tooltip that its size is not 0x0 or you can simply do an NSLog of the choresDictionary
like NSLog(#"%#",choresDictionary); I think your dictionary has 0 key key value pairs thats why you are getting null into your documents folder.
Thanks,
Madhup
I was running into this issue as well. In my case it turned out that I was using NSNumbers for keys - which is not valid.