tags:

views:

232

answers:

1

Hi, I am creating a method that is run once a user presses a button. The method creates a folder given the name defined by the user and adds a plist to that folder. The problem is that it doesn't create the plist. I know that the code works seperately, but I think that the plist creation is being done before the directory has been created. Is there any way to add a 'wait until' clause? Thanks

- (void) addTheDirectory{
NSString *theTitle = theTitleField.text;
NSString *theDescription = theDescriptionField.text;

//create the directory
[[NSFileManager defaultManager] createDirectoryAtPath:[NSString stringWithFormat:@"%@/%@", DOCUMENTS_FOLDER, theTitle] attributes:nil];

//create the plist
NSMutableDictionary* plistDictionary = [[NSMutableDictionary alloc] init];
[plistDictionary setValue:theTitle forKey:@"Title"];
[plistDictionary setValue:theDescription forKey:@"Description"];
[plistDictionary setValue:@"0.1" forKey:@"LBVersion"];
[plistDictionary writeToFile:[NSString stringWithFormat:@"%@/%@/info.plist", DOCUMENTS_FOLDER, theTitle] atomically: YES];
}
+2  A: 

createDirectoryAtPath:attributes: returns a BOOL so the code will not progress until the method creates the directory and returns.

I think this construction...

[NSString stringWithFormat:@"%@/%@/info.plist", DOCUMENTS_FOLDER, theTitle]

... is most likely your problem. It will usually work but the more robust method would be to use one of the dedicated path methods such as:

[NSString pathWithComponents:[NSArray arrayWithObjects:DOCUMENTS_FOLDER, theTitle,@"/info.plist",nil]]

This makes it more likely that you will get a correct path, especially if you just altered it.

You should also capture the boolean return from both file operations so you can see which one fails.

TechZen
Agreed: you should be checking the result of `-createDirectoryAtPath`. It's not guaranteed to succeed, and in your case, probably isn't.
Sixten Otto
It is succeeding because I can see the created directory. I think I need to look into threading. Thanks for the advise though.
Jack
I think threading is overkill. It's normal practice to create a directory and then immediately write to it.I've constructed entire populated hierarchies this way. Most code doesn't create a directory, wait a while, and then write something to it. Something else is wrong, most likely in the path construction. You could have an encoding problem in one of the variables used to create the path. Try constructing the path with one of the dedicated path methods and see if that helps. Just because the path to the directory works, doesn't mean the path to the file does.
TechZen
I would add that in debugging its important not to get fixated on a particular view of the problem. I had a similar problem where I thought I had a directory but I was actually looking at the wrong path in the simulator. Don't assume the createdirectory is working unless it reports that it is.
TechZen