Domanda

I am trying to create a class which has a method that receives a file path(NSString) as parameter.

I need to check the given file path is valid if it is valid I will do some writing operation on disk otherwise I ll return error.

So is it any best way to find out the given path is valid one?

È stato utile?

Soluzione

There is no need to check first if path is valid. Just go ahead and try to create it and then check for success.

createFileAtPath:contents:attributes: method of NSFileManager returns a BOOL that returns YES if the file already exists or did succeed in creating it.

I suggest using this method and check the returned result. If it returns NO then return error.

Altri suggerimenti

// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory {
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

For your example this would return

/var/mobile/Applications/8EFCBF99-BC19-4AFE-934A-B47CBEDF2971/Documents

Does that help you? I think the method is included in the AppDelegate of all Xcode project types that use Core Data.

Here is an example:

NSString *validPath = [[[self applicationDocumentsDirectory] path] stringByAppendingPathComponent:@"test"];
NSString *invalidPath = @"/var/mobile/Applications/abc/test";

if (0 == [validPath rangeOfString:[[self applicationDocumentsDirectory] path]].location) {
    // will be executed
    NSLog(@"Valid path");
}
else {
    NSLog(@"Invalid path");
}

if (0 == [invalidPath rangeOfString:[[self applicationDocumentsDirectory] path]].location) {
    NSLog(@"Valid path");
}
else {
    // will be executed
    NSLog(@"Invalid path");
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top