在OS X上获取当前用户的桌面路径 [英] Getting desktop path for current user on OS X

查看:112
本文介绍了在OS X上获取当前用户的桌面路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES );
NSString* theDesktopPath = [paths objectAtIndex:0];

它工作得很好。但是当我用sudo启动应用程序时,它会提供root的桌面路径。是否有任何方法来返回当前用户的桌面始终(即使应用程序是用sudo启动)?

It works well. But when I launch the application with sudo it gives the root's desktop path. Is there any way to return current user's desktop always (even if the app is started with sudo)?

推荐答案

是没有办法这样做的。但我可以解释为什么我认为。当您使用NSUserDomain时,它会缩小到活动用户的文件结构。所以像你说的,当你访问文件作为root用户,它使用根目录。它不能假设另一个用户的目录,因为如果有多个用户,它不会知道哪个是第一个运行它,因此不知道哪个桌面目录访问。

I would say there is no way to do this. But I can explain why I think that. When you use NSUserDomain it narrows down to the active user's file structure. So like you said when you're accessing files as the root user it uses root's directories instead. It couldn't assume the directories of another user because if there were multiple users it would not know which was running it in the first place and therefore not know which desktop directory to access.

我发现了一个方法,应该为你工作。而不是使用 NSSearchPathForDirectoriesInDomains ,你必须自己使用环境变量来构建路径。当在OS X上使用 sudo 时,它不会覆盖 $ HOME 变量,因此它维护调用者的主目录。您可以使用

I found a way around this that should work for you. Instead of using the NSSearchPathForDirectoriesInDomains you will have to build your path yourself using environment variables. When you use sudo on OS X it doesn't overwrite the $HOME variable so it maintains the caller's home directory. You can access all the environment variables with

[[NSProcessInfo processInfo] environment];

并取得 $ HOME >

and get $HOME with

[[[NSProcessInfo processInfo] environment] objectForKey:@"HOME"];

因此,您可以将 $ HOME 字符串并将 / Desktop 附加到它。这不会在沙箱中正常工作,但是因为你说的是​​以root身份运行它,我认为你不是。

So you can grab $HOME as a string and append /Desktop to it. This would not work correctly in a sandbox but since you're talking about running it as root I assume you're not.

这篇关于在OS X上获取当前用户的桌面路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆