Error while checking if a file exists - objective-c

I'm trying to write to a plist file using writeToFile, before I write I check whether the file exists.
This is the code:
#import "WindowController.h"
#implementation WindowController
#synthesize contacts;
NSString *filePath;
NSFileManager *fileManager;
- (IBAction)addContactAction:(id)sender {
NSDictionary *dict =[NSDictionary dictionaryWithObjectsAndKeys:
[txtFirstName stringValue], #"firstName",
[txtLastName stringValue], #"lastName",
[txtPhoneNumber stringValue], #"phoneNumber",
nil];
[arrayContacts addObject:dict];
[self updateFile];
}
- (void)awakeFromNib {
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
filePath = [rootPath stringByAppendingPathComponent:#"Contacts.plist"];
fileManager = [NSFileManager defaultManager];
contacts = [[NSMutableArray alloc] init];
if ([fileManager fileExistsAtPath:filePath]) {
NSMutableArray *contactsFile = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
for (id contact in contactsFile) {
[arrayContacts addObject:contact];
}
}
}
- (void) updateFile {
if ( ![fileManager fileExistsAtPath:filePath] || [fileManager isWritableFileAtPath:filePath]) {
[[arrayContacts arrangedObjects] writeToFile:filePath atomically:YES];
}
}
#end
When the addContactAction is executed I don't get any error but the program halts and it brings me to the debugger. When I press continue in the debugger I get:
Program received signal: “EXC_BAD_ACCESS”.
But that's probably not important.
PS: I'm new to mac programming and I don't know what else to try since I don't get an error message that tells me what's going wrong.
The path to the file is:
/Users/andre/Documents/Contacts.plist
I earlier tried this(with the same result), but I read that you can only write to the documents folder:
/Users/andre/Desktop/NN/NSTableView/build/Debug/NSTableView.app/Contents/Resources/Contacts.plist
Does anyone have an idea or even an explanation why this happens?

First, I think you shouldn't instantiate an NSFileManager object. Instead you use the default file manager, like this:
[[NSFileManager defaultManager] fileExistsAtPath: filePath];
Then, could you specify at which line the program is breaking into the debugger?

You are setting filePath with the stringByAppendingPathComponent: method. That method returns an autoreleased object. (Autoreleased object is used after it has been (automatically) released, which could cause the bad access error.)
I think changing
[rootPath stringByAppendingPathComponent:#"Contacts.plist"];
into
[[rootPath stringByAppendingPathComponent:#"Contacts.plist"] retain];
will solve your troubles.

Related

Read from file.Plist Returns Null

Program that Creates multiple Plist's Paths for Different information.
But only one path is not working.
(i think "writeToFile" is the problem)
code:
-(NSString *) createPath:(NSString *)withFileName
{
NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,
YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:withFileName];
return path;
}
Path
NSLog = /var/mobile/Applications/02CABC0A-6B5B-4097-A9D1-4336BE8230B7/Documents/MessagesDB.plist
&
-(void) messagesDbFlush
{
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[_messagesDB writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(#"ReturnsInfo is : %#", ReturnsInfo);
}
"ReturnsInfo" Array is Null :/
Anyone please help?
I once had the same error.
1) Check the name of the plist in the directory listing to match your coded one
2) Check Project settings, manually delete the pre-existing plist from the "Build Settings" > "Copy Bundle Resources", and drag drop from the list.
3) Select the plist in directory listing, check Utilities sidebar, check Identity & Type > Location as valid
4) If you deleted the app's "default" plist aka bundle identifier, add copy build phase, choose destination, choose pref folder as absolut path check "copy only when installing"
This solved my returning null.
And if all fails on the bundle identifier, you can always copy the plist to pref folder by code:
NSString *path = [#"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
BOOL PrefsExist=[[NSFileManager defaultManager] fileExistsAtPath:path];
NSString *copyPrefsPath = [#"~/Library/Preferences/com.MyCompany.MyApp.plist" stringByExpandingTildeInPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (PrefsExist == 0)
{
// Copy the plist to prefs folder (one-time event)
NSString *tessdataPath = [[NSBundle mainBundle] pathForResource:#"com.MyCompany.MyApp" ofType:#"plist"];
[fileManager copyItemAtPath:tessdataPath toPath:path error:&error];
} else
{
// Read/Write the values from plist
}
i have stored following array with 5 objects in it, its working fine on my side, try it
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5];
for(int i=0;i<5;i++)
[array addObject:#"This is Demo String, You can write your own String here"];
NSString *_fileMessagesDB = #"MessagesDB.plist";
// save it to the file for persistency
NSString *messagesDB_Path = [self createPath:_fileMessagesDB];
[array writeToFile:messagesDB_Path atomically:YES];
NSMutableArray *ReturnsInfo = [[NSMutableArray alloc ]initWithContentsOfFile:messagesDB_Path];
NSLog(#"ReturnsInfo is : %#", ReturnsInfo);

A function to write data to plist in Objective-c

Suppose I have a custom function called savePlist as below.
CommonClass.m
- (NSString *)getDirectoryPath
{
NSArray *pathList = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [pathList objectAtIndex:0];
return path;
}
- (void)savePlist:(NSString *)fileName WithArray:(NSArray *)fileArr
{
NSString *path = [[self getDirectoryPath] stringByAppendingPathComponent:fileName];
[fileArr writeToFile:path atomically:YES];
}
While I run a code as below, no plist is generated.
ABCAppDelegate.m
...
[cc savePlist:#"example.plist" WithArray:[NSArray new]];
The file of example.plist has not been generated, is there any mistakes on my code?
Thanks
UPDATE:
If I use the code as below, the xxx.plist file has been generated successfully.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *plistFile = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"abc.plist"];
NSMutableDictionary *plist = [[NSMutableDictionary alloc] initWithContentsOfFile:plistFile];
if (!plist) {
plist = [NSMutableDictionary new];
[plist writeToFile:plistFile atomically:YES];
NSLog(#"write plist");
}
Reference: link
UPDATE 2:
I change the code as below:
NSLog(#"code");
[cc savePlist:#"example.plist" WithArray:[NSArray new]];
NSLog(#"code");
- (void)savePlist:(NSString *)fileName WithArray:(NSArray *)fileArr
{
NSLog(#"fileName = %#, fileArr = %#", fileName, fileArr);
NSString *path = [[self getDirectoryPath] stringByAppendingPathComponent:fileName];
NSLog(#"path = %#", path);
[fileArr writeToFile:path atomically:YES];
}
It just print out:
2011-10-10 14:24:00.560 ABC[3390:207] code
2011-10-10 14:24:00.561 ABC[3390:207] code
No message of fileName = and fileArr =, also path = print out on the log, so the code inside savePlist have not been executed?
It looks like your common class object is not instantiated, and you are sending all those messages to nil. Try logging cc in your app delegate code, where you call this method from.
You need to create an instance of your common class, something like
cc = [[CommonClass alloc] init];
(may vary depending on your set up).

can't save plist. path is not writable

I'm saving a lot of informations in a plist. This one is by standart in my mainBundle.
this is my method to load the path and the data from the plist. if the file in the "application support" folder doesn't exist, i'm copying it from the mainBundle to there.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
self.plistPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.plist",plistName]];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager fileExistsAtPath: self.plistPath])
{
NSString *pathInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:#"plist"];
self.plist = [NSMutableDictionary dictionaryWithContentsOfFile:pathInBundle];
NSLog(#"plist doesnt exist");
}
else {
self.plist = [NSMutableDictionary dictionaryWithContentsOfFile:self.plistPath];
NSLog(#"plist exist");
}
NSLog(#"plist path: %#",self.plistPath);
if i add the following lines at the end, there's only NO the answer:
if([fileManager isWritableFileAtPath:self.plistPath]) NSLog(#"YES");
else NSLog(#"NO");
after all, i tried to save with [self.plist writeToFile:self.plistPath atomically:YES];, which is also not working.
sorry for answering so late - i had a lot of other stuff to do. back to my problem: i only get the error, when i try to add a new entry to my dictionary (plist). editing is no problem. i think the problem is, how i try to add the entry. my code looks like:
NSMutableDictionary *updateDict = [[self.plist objectForKey:#"comments"]mutableCopy];
NSMutableDictionary *tmpDict = [[[NSMutableDictionary alloc]init]autorelease];
[tmpDict setObject:comment forKey:#"comment"];
[tmpDict setObject:author forKey:#"author"];
[tmpDict setObject:car forKey:#"car"];
[tmpDict setObject:part forKey:#"part"];
[tmpDict setObject:date forKey:#"date"];
[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]];
[self.plist setObject:updateDict forKey:#"comments"];
if([self.plist writeToFile:self.plistPath atomically:YES]) {
return YES;
}
else {
return NO;
}
self.plist is my local copy of the file at plistPath. the structure of my plist looks like: https://img.skitch.com/20111026-tcjxp9ha4up8ggtfjy7ucgqcqe.png
hope this helps
Ok, so that's not the Documents directory and iOS doesn't have an Application Support directory created in the sandbox by default, which is why you can't write.
You can either change your method call to look-up the real documents directory:
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
Or, after you get the path to the Application Support directory, you must check to see if it exists already and if not, create it.
please go through the previous post which shows the different way to copy the plist from mainBundle. Use [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error]; method instead.
Did you find answer? if not, you need to change this line:
[updateDict setObject:tmpDict forKey:[NSNumber numberWithInt:[updateDict count]+1]];
to
[updateDict setObject:tmpDict forKey:[NSString stringWithFormat:#"%d",[updateDict count]+1]];
Key name is string, not object.

NSFileManager FileSize Problem - Cocoa OSX

I have a function that checks the size of several plist files in the /User/Library/Preferences/ directory. For testing purposes, I'm using iTunes, which on my machine has a preference file of ~500kb.
EDIT: I have corrected my code as per the answer - as posted, this code works correctly.
NSString *obj = #"iTunes";
NSString *filePath = [NSString stringWithFormat:#"/Applications/%#.app",obj];
NSString *bundle = [[NSBundle bundleWithPath:filePath] bundleIdentifier];
NSString *PropertyList=[NSString stringWithFormat:#"/Preferences/%#.plist",bundle];
NSString* fileLibraryPath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingString:PropertyList];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fileLibraryPath];
if (fileExists) {
NSError *err = nil;
NSDictionary *fattrib = [[NSFileManager defaultManager] attributesOfItemAtPath:fileLibraryPath error:&err];
if (fattrib != nil){
//Here I perform my comparisons
NSLog(#"%i %#", [fattrib fileSize],obj);
}
}
However, no matter what I do, the size is returned as 102. Not 102kb, just 102. I have used objectForKey:NSFileSize, I have used stringValue, all 102.
As stated in the selected answer below lesson learned is to always check the path you're submitting to NSFileManager.
Thanks!
The filePath that you are using in
NSDictionary *fattrib = [ ... attributesOfItemAtPath:filePath error:&err];
appears to be
/Applications/iTunes.app
which on my system is a directory of size 102 bytes, same for /Applications/Mail.app - 102 bytes. Is it just that the path is not what you intend?

ObC : app crashes after returning NSMutableArray?

I am new to ObC and have a problem that i just cant fix. There may be other issues as well but the main issue is this:
Starting the app
Press button = load new view
In the new viewDidLoad i call another object/function and send a NSMutableArray
Process data and send back a NSMutableArray
App crash, see comment where. Most often when i go back and back again but sometimes the first time
As i am new to this i guess i do a lot of this wrong but could someone nice take a look at the code and give me some advice. I would assume i have problem with releasing something.
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#" ");
NSLog(#"viewDidLoad ");
NSLog(#" ");
NSLog(#">>Processing prepareGame<<");
NSMutableArray *propArray1 = [[NSMutableArray alloc] initWithObjects:#"9999", nil]; //Init with dummy numbers
AccessPropertiesFile *readMyProperties = [AccessPropertiesFile new]; //Init function call to read file
NSLog(#"Prepare to call readProperties");
propArray1 = [readMyProperties readPropertiesFile:propArray1];
NSLog(#"Back from readProperties:error after this");
/*
for (NSString *element in propArray1) {
NSLog(#"Elements in prop2Array; %#", element);
}
*/
[readMyProperties release];
[propArray1 release];
}
-(NSMutableArray *)readPropertiesFile:(NSMutableArray *)readDataArray {
NSLog(#"Processing readProperties");
// For error information
NSError *error;
//Prepare File Manager
NSString *filePath = [self dataFilePath];
NSFileManager *fileMgr;
fileMgr = [NSFileManager defaultManager];
NSArray *propertiesArray = [NSArray alloc]; //Alloc array
//Check from what module the call is coming from to ecide what to do
if ([fileMgr fileExistsAtPath: filePath] == NO) {
NSLog (#"File not found");
//File does not exists, this is the first time the game starts
//Set up default parameters
NSString *fileString =#"0\n30\n30\n10\n1\n1\n1\n2\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n1\n";
// Write default parameters to file
[fileString writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
propertiesArray = [fileString componentsSeparatedByString:#"\n"]; // each line, adjust character for line endings
}
else { //File exists
NSLog (#"File exists");
NSString *fileString = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding error:nil]; // reads file into memory as an NSString
propertiesArray = [fileString componentsSeparatedByString:#"\n"]; // each line, adjust character for line endings
}
//Clean readDataArray
[readDataArray removeAllObjects];
//Populate return array
for (NSString *element in propertiesArray) {
//NSLog(#"Elements in propertiesArray; %#", element);
[readDataArray addObject:element];
}
NSLog(#"readDataArray: %#", readDataArray);
[propertiesArray release];
[readDataArray autorelease];
NSLog(#"returning from readProperties");
return readDataArray;
}
#end
You are over-releasing readDataArray (known as propArray1 in the method that didn't create it). You create it and autorelease it in your second method, then you release it again at the end of your first method (where it wasn't created).
I suggest you use Analyze feature that comes with latest XCode. It is a good feature that I always use to track if I forget to release or release too much.
I also spotted that you also over-release the propertiesArray because it contains the result from [fileString componentsSeparatedByString:], which will be autorelease according to Cocoa convention.