Mac OS X编程中如何获取UUID

Gur*_*put 3 macos cocoa objective-c

我正在尝试使用以下代码在 Cocoa 编程中访问 Mac OS X UUID:

NSString *uuid = [[NSUUID UUID] UUIDString];
Run Code Online (Sandbox Code Playgroud)

每次我访问 uuid 时,uuid 都会返回一个唯一的 id,即使我没有重新安装应用程序,它也会不断变化。我需要知道如何在 Mac OS X 中访问 UUID,该 UUID 将保持不变;无论我重新安装应用程序还是重新编译,它都应该保持不变。

在 iOS 中,我可以使用以下代码实现相同的目的:

NSString *iosuuid = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
Run Code Online (Sandbox Code Playgroud)

这里 iosuuid 返回 uuid,即使我重新安装和重新编译我的应用程序,它也将保持不变。

不要建议我使用 Mac 地址,我不想在我的应用程序中出于某些目的而访问该地址。

d32*_*223 5

如果有人在寻找简单的 Objective-C 解决方案时遇到这个问题 - 下面的实现对我有用(在 macOS 11.2 上测试):

#import <IOKit/IOKitLib.h>

- (NSString *) getUUID {
    io_service_t platformExpert = IOServiceGetMatchingService(kIOMasterPortDefault,IOServiceMatching("IOPlatformExpertDevice"));
    if (!platformExpert) return nil;

    CFTypeRef serialNumberAsCFString = IORegistryEntryCreateCFProperty(platformExpert,CFSTR(kIOPlatformUUIDKey),kCFAllocatorDefault, 0);

    IOObjectRelease(platformExpert);

    if (!serialNumberAsCFString) return nil;

    return (__bridge NSString *)(serialNumberAsCFString);;
}
Run Code Online (Sandbox Code Playgroud)

编译添加IOKit框架:

gcc -fobjc-arc -framework Cocoa -framework IOKit -x objective-c sources/** main.m -o app.bin
Run Code Online (Sandbox Code Playgroud)

您可以简单地调用此函数:

int main () {
    ..
    NSString *uuid = self.getUUID;
    NSLog(@"uuid: %@", uuid);
    ..
}
Run Code Online (Sandbox Code Playgroud)