views:

28

answers:

2

I have a piece of code which is said to return a bool value. I am a new programmer, so could someone give me code that will determine if the file at the path exists?

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"]; //returns a bool
A: 

If a variable contains a boolean value, you can just test it whith:

if(var) {
   // gets executed if var is true
}

Read about conditional control structurs.

But stringByAppendingPathComponent does not return a boolean value, it returns a string.

Felix Kling
+1  A: 

Actualy the stringByAppendingPathComponent: method does not return (BOOL) it returns (NSString *).

You can tell by looking at its signature which is:

- (NSString *)stringByAppendingPathComponent:(NSString *)str;

If it did return a bool (which it does not,) all you would have to do is: if (path) {//...}

What you actually want to do to test if a file exists is:

NSString *docsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *path = [docsDirectory stringByAppendingPathComponent:@"fileName.txt"]; 
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory]) {
  //File Exists So Code Goes Here
}
Brad Smith