Mac的唯一标识符?

San*_*ier 24 macos cocoa uniqueidentifier

在我可以使用的iPhone上

[[UIDevice currentDevice] uniqueIdentifier];
Run Code Online (Sandbox Code Playgroud)

获取标识此设备的字符串.OSX中有什么相同的东西吗?我没找到任何东西.我只想确定启动该应用程序的Mac.你能帮助我吗 ?

Jar*_*die 32

苹果拥有的技术说明上唯一识别MAC.这是Apple在该技术说明中发布的代码的松散修改版本...不要忘记链接您的项目IOKit.framework以构建此代码:

#import <IOKit/IOKitLib.h>

- (NSString *)serialNumber
{
    io_service_t    platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,

    IOServiceMatching("IOPlatformExpertDevice"));
    CFStringRef serialNumberAsCFString = NULL;

    if (platformExpert) {
        serialNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert,
                                                         CFSTR(kIOPlatformSerialNumberKey),
                                                             kCFAllocatorDefault, 0);
        IOObjectRelease(platformExpert);
    }

    NSString *serialNumberAsNSString = nil;
    if (serialNumberAsCFString) {
        serialNumberAsNSString = [NSString stringWithString:(NSString *)serialNumberAsCFString];
        CFRelease(serialNumberAsCFString);
    }

    return serialNumberAsNSString;
}
Run Code Online (Sandbox Code Playgroud)


Jos*_*zzi 17

Swift 2答案

这个答案增加了Jarret Hardie 2011年的答案.这是一个Swift 2 String扩展.我添加了内联注释来解释我做了什么以及为什么,因为导航是否需要释放对象在这里可能会很棘手.

extension String {

    static func macSerialNumber() -> String {

        // Get the platform expert
        let platformExpert: io_service_t = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IOPlatformExpertDevice"));

        // Get the serial number as a CFString ( actually as Unmanaged<AnyObject>! )
        let serialNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert, kIOPlatformSerialNumberKey, kCFAllocatorDefault, 0);

        // Release the platform expert (we're responsible)
        IOObjectRelease(platformExpert);

        // Take the unretained value of the unmanaged-any-object 
        // (so we're not responsible for releasing it)
        // and pass it back as a String or, if it fails, an empty string
        return (serialNumberAsCFString.takeUnretainedValue() as? String) ?? ""

    }

}
Run Code Online (Sandbox Code Playgroud)

或者,函数可以返回String?,最后一行不能返回空字符串.这可能会更容易识别无法检索序列号的极端情况(例如在他对Jerret的回答的评论中提到的修复的Mac主板情景哈里斯).

我还用仪器验证了正确的内存管理.

我希望有人发现它有用!