5
我正在使用NSFileManager setAttributes來更改目錄的權限。我的問題是,它似乎不遞歸。有什麼辦法可以強制它這麼做嗎?如何使用NSFileManager遞歸地更改目錄的權限setAttributes
我正在使用NSFileManager setAttributes來更改目錄的權限。我的問題是,它似乎不遞歸。有什麼辦法可以強制它這麼做嗎?如何使用NSFileManager遞歸地更改目錄的權限setAttributes
我不認爲有一個內置的方法來做到這一點,但它不應該是很難做這樣的事情:
NSString *path = @"/The/root/directory";
NSDictionary *attributes; // Assume that this is already setup
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
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
}
}
}
這是未經測試,但應該給你一個起點。
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];
}
}