Creating a plist with multiple strings - objective-c

I have a multiple strings I would like to write to one plist using objective c. Can anyone please tell me exactly how to do this? I appreciate it

As H2CO3 hinted, you could use NSArray's writeToFile:atomically: method.
For example:
NSArray *arr = #[
#"my first string",
#"my second string",
#"and the last one"
];
[arr writeToFile:#"./out.plist" atomically:NO]; // Or YES depending on your needs

Here's one possibility:
// Create the path that you want to write your plist to.
NSError *error = nil;
NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
if (documentsURL == nil) {
NSLog(#"Error finding user documents in directory: %#", [error localizedDescription]);
return nil;
}
NSString *path = [[documentsURL path] stringByAppendingPathComponent:#"YourFile.plist"];
// Populate your strings and save to the plist specified in the above path.
NSString *kRoot = #"kRoot";
NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
tempDict[kRoot] = [NSMutableArray array];
[tempDict[kRoot] addObject:#"String 1"];
[tempDict[kRoot] addObject:#"String 2"];
[tempDict[kRoot] addObject:#"String 3"];
// Etc, add all your strings
if (![tempDict writeToFile:path atomically:YES])
{
NSLog(#"Error writing data to path %#", path);
}

Related

Writing NSArray into plist

I'm trying to save a NSMutableArray into a pre-existing plist.
When I try:
NSError *errorDesc;
NSPropertyListFormat format;
NSString *plistPath;
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:#"Array_Label_Generiche.plist"];
if (![[NSFileManager defaultManager] fileExistsAtPath:plistPath]) {
NSLog(#"prima volta");
plistPath = [[NSBundle mainBundle] pathForResource:#"Array_Label_Generiche" ofType:#"plist"];
}
NSData *plistXML = [[NSFileManager defaultManager] contentsAtPath:plistPath];
NSMutableArray *temp = (NSMutableArray *)[NSPropertyListSerialization
propertyListFromData:plistXML
mutabilityOption:NSPropertyListMutableContainersAndLeaves
format:&format
errorDescription:&errorDesc];
if (!temp) {
NSLog(#"Error reading plist: %#, format: %lu", errorDesc, format);
}
contatore = (int)temp.count ;
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
[dictionary setObject:array_copiato forKey:[NSString stringWithFormat: #"%#", [alertView textFieldAtIndex:0].text]];
NSDictionary *dictionary_da_salvare = [[NSDictionary alloc ] initWithDictionary: dictionary];
//AGGIUNGO I DATI CREATI
NSLog(#"TEMP %#",temp);
[temp addObject:dictionary_da_salvare];
BOOL didWriteArray = [temp writeToFile:plistPath atomically:YES];
if (didWriteArray)
{
NSLog(#"Write to .plist file is a SUCCESS!");
}
else
{
NSLog(#"Write to .plist file is a FAILURE!");
}
In this case, output show me that "Write to .plist file is a FAILURE!".
In the Apple Guide, I read that I must serialize data before writing on the plist.
Then I tried to write these lines of code:
NSData *plistData = [NSPropertyListSerialization dataFromPropertyList:temp format:NSPropertyListXMLFormat_v1_0 errorDescription:&errorDesc];
if(plistData == nil){
NSLog (#"error writing to file: %#", errorDesc);
}
When I run the application, the output area reads:
error writing to file: Property list invalid for format (property
lists cannot contain objects of type 'CFType') Write to .plist file
is a FAILURE!
I think because the array test is NSMutableArray because I have read in the Apple Guide:
The NSPropertyListSerialization class provides methods that convert
property list objects to and from several serialized formats. Property
list objects include NSData, NSString, NSArray, NSDictionary, NSDate,
and NSNumber objects. These objects are toll-free bridged with their
respective Core Foundation types (CFData, CFString, and so on).

Mac os x writeToFile not working using xcode5

I'm trying to modify a plist and saving the changes but it doesn't work:
here is my code:
NSString *myPath = [[NSBundle mainBundle] pathForResource:#"myPlist" ofType:#"plist"];
NSMutableDictionary *plistDict;
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[plistDict objectForKey:#"$objects"]];
for (int i =0 ; i <array.count; i++)
{
if ([[array objectAtIndex:i] isKindOfClass:[NSString class]])
{
if ([[array objectAtIndex:i] isEqualToString:#"myString"])
{
[[plistDict objectForKey:#"$objects"]replaceObjectAtIndex:i withObject:#"newString"];
}
}
}
NSString *root = #"/Users/myUser/Desktop/newPlist.plist";
[plistDict writeToFile:root atomically:YES];
the dictionary of the content is been modify and I don't have any errors but the file is never been created in the path. Any of you know what I'm doing wrong? or how can I fixed?
I suspect that you are writing to a Sandboxed location. Not actually to the users directory.
Refer the below code:-
NSMutableDictionary *plistDict=//assuming your data
NSString *root = #"/Users/home/Desktop/newPlist.plist";
if (![[NSFileManager defaultManager]fileExistsAtPath:root])//checking fileexist or not
{
//if not exist creating the same
[[NSFileManager defaultManager]createFileAtPath:root contents:nil attributes:nil];
[plistDict writeToFile:root atomically:YES];
}
else
{
[plistDict writeToFile:root atomically:YES];
}

.m file to string

I am trying to convert a .m file to string. I will search for files in a folder and then want to use each of its contents as a string. This is the code I am using:
- (IBAction)searchAction:(id)sender {
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:folderLabel.stringValue error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:#"self ENDSWITH '.m'"];
NSArray *onlyMs = [dirContents filteredArrayUsingPredicate:fltr];
for (int i=0; i<[onlyMs count]; i++) {
NSString* text = [[NSString alloc] initWithContentsOfFile:[onlyMs objectAtIndex:i]
encoding:NSUTF8StringEncoding
error:nil];
NSLog(#"string: %#", text);
}
}
2013-02-13 02:38:05.700 LocalizedStringSearch[19001:303] string: (null)
Except here, all the log is returning is null even though it will find all the .m file correctly.
Anyone know what I'm doing wrong?
Thanks a lot!
I think contentsOfDirectoryAtPath: gives you an array of filenames only, not full path names, so you need to prepend the path before you open files. EDIT: I think I might be confusing that with enumeratorAtPath:... if so continue using the filenames you have rather than appending them to the original folder name.
Here's an example (untested):
NSString *fullPath = [folderLabel.stringValue stringByAppendingPathComponent:[onlyMs objectAtIndex:i];
NSError *error = nil;
NSString *text = [[NSString alloc] initWithContentsofFile:fullPath
encoding:NSUTF8StringEncoding
error:&error];
if (text == nil)
NSLog(#"%#", error);
else
NSLog(#"%#", text);
The above will only work if the files actually are encoded using UTF-8. If you are unsure of the encoding, you can let the framework try and figure it out for you with:
NSString *fullPath = [folderLabel.stringValue stringByAppendingPathComponent:[onlyMs objectAtIndex:i];
NSError *error = nil;
NSStringEncoding enc;
NSString *text = [[NSString alloc] initWithContentsofFile:fullPath
usedEncoding:&enc
error:&error];
if (text == nil)
NSLog(#"%#", error);
else
NSLog(#"%#", text);

Can't figure out about saving files

I am trying to save my object to the file system on an iPad, but I seem to be doing something wrong. Here is how I have archived the object:
NSString *localizedPath = [self getPlistFilePath];
NSString *fileName = [NSString stringWithFormat:#"%#.plist", character.infoName];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:character];
fileName = [fileName stringByReplacingOccurrencesOfString:#" " withString:#"_"];
localizedPath = [localizedPath stringByAppendingPathComponent:fileName];
NSLog(#"File Path: %#", localizedPath);
if(data) {
NSError *writingError;
BOOL wasWritten = [data writeToFile:localizedPath options:NSDataWritingAtomic error:&writingError];
if(!wasWritten) {
NSLog(#"%#", [writingError localizedDescription]);
}
}
Now, this creates a plist file that I can see and read on the file system. When I try to use the following to unarchive it though:
NSError *error;
NSString *directory = [self getPlistFilePath];
NSArray *files = [[NSFileManager defaultManager]contentsOfDirectoryAtPath:directory error:&error];
NSMutableArray *characters = [[NSMutableArray alloc]init];
for(NSString *path in files) {
if(![path hasSuffix:#"plist"]) {
continue;
}
NSString *fullPath = [directory stringByAppendingPathComponent:path];
NSData *data = [NSData dataWithContentsOfFile:fullPath];
IRSkillsObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data]; // get EXEC_BAD_ACCESS here...
[data release];
[characters addObject:object];
}
I get an EXEC_BAD_ACCESS error.
The IRSkillsObject conforms to the NSCoding protocol. You can see, I commented the line that I get the error on.
I am sure it's something I am doing wrong, but I just can't see it. I have tried to step through with the debugger (placing a break point in the initWithCoder: method of the object) but I don't get any errors then. In fact, it places the data in the object properly as I watch. But once it's done loading the data, it gives the error. I have tried using the retain method, but that doesn't help.
Any help that you can provide would be greatly appreciated!
You are releasing data without allocating it.
NSData *data = [NSData dataWithContentsOfFile:fullPath];
IRSkillsObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[data release];
So try this:
NSData *data = [[NSData alloc] initWithContentsOfFile:fullPath];
IRSkillsObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
[data release];
When an EXEC_BAD_ACCESS error is found. Usually is because some data has been released but it is still needed in the code.
Maybe there is a property inside your IRSkillsObject not retained in -initWithCoder:

Creating an array from documentsDirectory includes ends with .MOV

I want to create a NSArray from my app sandbox's documentsDirectory's includes. It includes so many files, but my array will only be by the ones ends with .MOV.
Can you help me?
Thank you!
There are a couple of options using the NSFileManager.
NSString *path = #"<dir_path>";
//Option 1 using directory enumerator
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:path];
NSMutableArray *movfiles = [NSMutableArray array];
while(NSString *file = [direnum nextObject])
{
if([[file pathExtension] isEqualToString:#"MOV"])
[movfiles addObject:movfiles];
}
//Option 2 case insensitive using a predicate
NSError *error;
NSArray *dircontents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
if(error)
{
//Handle error
}
else
{
dircontents = [dircontents filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"pathExtension ==[c] %#", #"mov"]];
}