views:

111

answers:

3

I'm sure there is a better way to do this. I have this chunk of code that I use to wipe out the DocumentsDirectory on an iPhone or Simulator. Sometimes I just want a clean slate, and sometimes I make changes to a database and I need to rebuild it.

So, in one of my functions that gets called when I turn on my app, I have this code commented out, and I remove the comment block when I want to reset. What do you do?

NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSArray *dirContents = [fileManager directoryContentsAtPath:[paths objectAtIndex:0]];

for (int i=0; i<[dirContents count]; ++i) {
  NSString* theDir = [[paths objectAtIndex:0] stringByAppendingString:[@"/" stringByAppendingString:[dirContents objectAtIndex:i]]];
  NSLog(theDir);
  if ([fileManager removeItemAtPath: theDir error:NULL]) {
    NSLog(@"removed dir");
  }
}

I'm a novice iPhone developer. If this were something like a Python server, I'd just have a script I run, but I'm not sure what the XCode/iPhone convention for this is.

+1  A: 

I believe that's how you have to do it... apps are "sandboxed" so you won't be able to get to the documents directory any other way. (But please someone correct me if I'm wrong!)

Alternatively, you can erase the app (hold down on it and tap the X in the home screen) before building, to wipe any data.

mjhoy
+5  A: 

I typically just delete the app from the simulator each time I need to clear this directory.

Dan Lorenc
+2  A: 

Your method looks about like what I'd do. However, you can change this:

[... stringByAppendingString:[@"/" stringByAppendingString:[dirContents objectAtIndex:i]]];

to this:

[... stringByAppendingPathComponent:[dirContents objectAtIndex:i]];
BJ Homer