Date
Sep. 8th, 2024
 
2024年 8月 6日

Post: OS X: How to get the path of Home directory

OS X: How to get the path of Home directory

Published 12:04 Apr 12, 2016.

Created by @ezra. Categorized in #Programming, and tagged as #macOS.

Source format: Markdown

Table of Content

We all know that NSHomeDirectory() is retuning the sandbox root (not the home directory), [@"~" stringByExpandingTildeInPath] is doing the same thing.

This /Users/username/Library/Containers/appID/Data is what's being returned.

The only thing its really good for is setting a sane default to the file open/save dialogs. Right now, if we set it to NSHomeDirectory() its not very user friendly. Most people don't even know what the Library folder is.

So, how do we get /Users/username/?

Here's a example:

// MXCocoaHelper.m
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <assert.h>

NSString * NSRealHomeDirectory(void) {
    struct passwd *pw = getpwuid(getuid());
    assert(pw);
    return [NSString stringWithUTF8String:pw->pw_dir];
}

This gives you the path to the user's home, but does not automatically give you access to that folder. You can use this path for:

  • Providing a sane default folder for the open/save dialogs
  • Detecting whether you are in a sandbox, by comparing the result to NSHomeDirectory()
Pinned Message
HOTODOGO
The Founder and CEO of Infeca Technology.
Developer, Designer, Blogger.
Big fan of Apple, Love of colour.
Feel free to contact me.
反曲点科技创始人和首席执行官。
程序猿、设计师、奇怪的博主。
苹果死忠、热爱色彩斑斓的世界。
如有意向请随时 与我联系