Reputation: 6552
New to objective-c. How do I get the directory from a full file path?
so if I have
/User/Test/Desktop/test.txt
I want
/User/Test
Also is there an equivalent to Path.Combine from .NET in Objective-C?
Upvotes: 2
Views: 2547
Reputation: 53000
Read the Working with Paths section of Apple's NSString
documentation, you will find methods that answer your questions. For example, stringByDeletingLastPathComponent
removes the last component of a path leaving the containing directory.
Upvotes: 4
Reputation: 108091
-[NSString pathComponents]
returns an NSArray
of path components.
For instance
NSString *path = @"/User/Test/Desktop/test.txt";
NSArray *components = [path pathComponents];
NSLog(@"%@", components); //=> ( /, User, Test, Desktop, test.txt )
Then you can take only the components you need and build a new path with them, for instance
NSString *newPath =
[NSString pathWithComponents:
[components subarrayWithRange:(NSRange){ 0, components.count - 2}]];
NSLog(@"%@", newPath); // => /User/Test/
Upvotes: 4