我需要修改我的文件属性。有一个属性 NSFileGroupOwnerAccountID
苹果说它可以修改但是当我修改它时,它没有得到更新。
我也试过先修改0777的权限,还是不行。
代码:
NSFileManager *filemgr;
NSDictionary *attribs;
NSArray *dirPaths;
NSString *docsDir;
filemgr =[NSFileManager defaultManager];
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSArray * filePathsArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: docsDir error:NULL];
NSError *error;
for(int i=0;i<[filePathsArray count];i++)
{
NSString *filePath = [filePathsArray objectAtIndex:i];
NSString *fullPath = [docsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",filePath]];
attribs = [filemgr attributesOfItemAtPath:
docsDir error: NULL];
NSLog (@"POSIX Permissions %@", [attribs objectForKey: NSFilePosixPermissions]);
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary:attribs];
[attributes setValue:[NSNumber numberWithShort:0777]
forKey:NSFilePosixPermissions]; // chmod permissions 777
[[NSFileManager defaultManager]setAttributes:attributes ofItemAtPath:docsDir error:&error];
NSLog(@"updated: %@",[filemgr attributesOfItemAtPath:
docsDir error: NULL]);
NSDictionary *dict2 = [filemgr attributesOfItemAtPath:
docsDir error: NULL];
NSMutableDictionary *attributes2 = [NSMutableDictionary dictionaryWithDictionary:dict2];
[attributes2 setValue:[NSNumber numberWithUnsignedLong:12345]forKey:NSFileGroupOwnerAccountID];
[[NSFileManager defaultManager]setAttributes:attributes2 ofItemAtPath:docsDir error:&error];
NSLog(@"updated2: %@",[filemgr attributesOfItemAtPath:
docsDir error: NULL]);
}
“ URL ”
更新 2:
只修改单个属性:
NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
[attributes setValue:[NSNumber numberWithUnsignedLong:12345]forKey:NSFileGroupOwnerAccountID];
BOOL check= [[NSFileManager defaultManager]setAttributes:attributes ofItemAtPath:docsDir error:&error];
还是报错:
Error Domain=NSCocoaErrorDomain Code=513 "The operation couldn’t be completed. (Cocoa error 513.)" UserInfo=0x8d0b900 {NSFilePath=/Users/a/Library/Application Support/iPhone Simulator/7.1/Applications/81ADKJ1A2-B612-4784-9524-05456F323212/Documents, NSUnderlyingError=0x8d11b80 "The operation couldn’t be completed. Operation not permitted"}
请建议如何修改属性。
提前致谢。
最佳答案
除非您以 super 用户身份运行,否则您只能更改您拥有的文件组。此外,您只能将群组更改为您所属的群组。
您不应该使用包含文件当前属性的字典。构造一个仅包含您要更改的属性的字典。否则,系统可能会认为您正在尝试“更改”您不是的属性并失败,因为它无法完成您(显然)要求的所有事情。
您应该检查 -setAttributes:ofItemAtPath:error:
方法的返回值,看它是否失败。如果是,您需要检查它提供的错误对象以了解原因。
更新:顺便说一句,对于这些类型的文件操作,您始终可以使用 POSIX API。有时,Cocoa 并不是低级操作的最佳 API,更接近金属可以更清晰。
int result;
do
{
result = chown([docsDir fileSystemRepresentation], -1, 12345);
}
while (result != 0 && errno == EINTR);
if (result != 0)
/* handle error; examine errno to learn failure reason */;
(不过,在这种情况下,根据您记录的错误判断,我确定 errno
将是 EPERM
(1)。)
关于ios - 修改 NSFileManager 中文件的 NSFileGroupOwnerAccountID 属性未获得更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23758122/