How to change permission of a directory recursively using NSFileManager setAttributes
I'm currently using NSFileManager setAttributes to change the permission of a direc开发者_开发问答tory. My problem is that it doesn't appear to do so recursively. Is there any way to force it to do so?
I don't think there's a built-in method to do this, but it shouldn't be hard to do something like:
NSString *path = @"/The/root/directory";
NSDictionary *attributes; // Assume that this is already setup
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *subPaths = [fileManager subpathsAtPath:path];
for (NSString *aPath in subPaths) {
BOOL isDirectory;
[fileManager fileExistsAtPath:aPath isDirectory:&isDirectory];
if (isDirectory) {
// Change the permissions on the directory here
NSError *error = nil;
[fileManager setAttributes:attributes ofItemAtPath:aPath error:&error];
if (error) {
// Handle the error
}
}
}
This is untested, but should give you a starting point.
NSString *path = @"/User/user/aPath";
NSFileManager *manager = [[[NSFileManager alloc] init] autorelease];
if ([manager fileExistsAtPath: path]) {
NSDictionary *attrib = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:0], NSFileGroupOwnerAccountID,
[NSNumber numberWithInt:0], NSFileOwnerAccountID,
@"root", NSFileGroupOwnerAccountName,
@"root", NSFileOwnerAccountName, nil ];
NSError *error = nil;
[manager setAttributes:attrib ofItemAtPath:path error:&error];
NSDirectoryEnumerator *dirEnum = [manager enumeratorAtPath: path];
NSString *file;
while (file = [dirEnum nextObject]) {
[manager setAttributes:attrib ofItemAtPath:[path stringByAppendingPathComponent:file] error:&error];
}
}
精彩评论