2014-06-20 132 views
0

我有一个应用程序在根目录下运行,并更改用户创建的某个文件。 问题是,使用我的应用程序编辑文件后,它会成功保存,但会更改文件的所有者。 编辑如此前的文件是:NSFileManager更改文件所有者/权限

[email protected] 1 myusername wheel 2418 Jun 18 18:29 myfile.plist 

编辑完成后:

[email protected] 1 root wheel 2418 Jun 18 18:29 myfile.plist 

这是我如何编辑文件代码:

NSMutableDictionary* myFile = [NSMutableDictionary dictionaryWithContentsOfFile:@"myFile.plist"]; 
[myFile setObject:@"some text" forKey:@"some key"]; 
BOOL result = [myFile writeToFile:@"myFile.plist" atomically:YES]; 

我需要保持文件的所有者,即使编辑后在根目录下使用应用。 我该如何解决上述问题?

编辑:我尝试下面的代码,并返回成功的结果,但不会更改的权限:

NSDictionary *properties = [[NSFileManager defaultManager] attributesOfItemAtPath:@"myfile.plist" 
                      error:nil]; 

NSMutableDictionary *newProperties = [NSMutableDictionary dictionaryWithDictionary:properties]; 
[newProperties setObject:@"myusername" forKey:NSFileOwnerAccountName]; 

NSError *error = nil; 

BOOL result = [[NSFileManager defaultManager] setAttributes:newProperties 
               ofItemAtPath:@"myfile.plist" 
                 error:&error]; 

回答

1

我相信只有NSNumber的对象都接受attributesOfItemAtPath权限。尝试使用的AccountID代替:(NSFileOwnerAccountID和/或NSFileGroupOwnerAccountID):

NSMutableDictionary *newProperties = [NSMutableDictionary dictionaryWithDictionary:properties]; 
      [newProperties setObject:[NSNumber numberWithInt:0] forKey:NSFileOwnerAccountID]; 

从苹果文档

NSFilePosixPermissions值必须与 表示POSIX文件级的代码进行初始化权限位模式,其中 对应的值是一个NSNumber对象。

参考:NSFileOwnerAccountID

0

您可以使用NSFileManagersetAttributes:ofItemAtPath:error:法的NSFileImmutable属性:

NSDictionary* attribs = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSFileImmutable]; 
[[NSFileManager defaultManager] setAttributes: attribs ofItemAtPath:@"/path/to/file" error:nil]; 

希望这有助于!