简体   繁体   English

在Cocoa中获取Mac型号

[英]Getting Mac Model number in Cocoa

I'm making a OS X app where I need to get the Mac model, for example: 我正在制作一个OS X应用程序,我需要获取Mac模型,例如:

iMac11,3
MacBook3,1

And so on. 等等。 Is there any class, or function to get it? 是否有任何课程或功能得到它?

This information is available via. 这些信息可通过。 sysctl : sysctl

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/sysctl.h>

size_t len = 0;
sysctlbyname("hw.model", NULL, &len, NULL, 0);
if (len) {
    char *model = malloc(len*sizeof(char));
    sysctlbyname("hw.model", model, &len, NULL, 0);
    printf("%s\n", model);
    free(model);
}

The API for that would be in the IOKit. 它的API将在IOKit中。 Looking in the IORegistryExplorer app on my laptop, I see that the first node from the root of the IOService tree is an IOPlatformExpertDevice, with a entry under the key "model" equal to "MacBookPro6,1" 在我的笔记本电脑上查看IORegistryExplorer应用程序,我看到IOService树根的第一个节点是IOPlatformExpertDevice,在“model”键下的条目等于“MacBookPro6,1”

While not using a direct Cocoa API, you could use NSTask to execute the "system_profiler" command line tool. 虽然不使用直接Cocoa API,但您可以使用NSTask来执行“system_profiler”命令行工具。 If you execute the tool as: "system_profiler SPHardwareDataType" it will give you a smaller output which could be filtered to extract the model identifier. 如果您执行以下工具:“system_profiler SPHardwareDataType”,它将为您提供较小的输出,可以对其进行过滤以提取模型标识符。

Update 更新

I found an example using sysctl programmatically: 我找到了一个以编程方式使用sysctl的示例:

int mib[2];
size_t len = 0;
char *rstring = NULL;

mib[0] = CTL_HW;
mib[1] = HW_MODEL;
sysctl( mib, 2, NULL, &len, NULL, 0 );
rstring = malloc( len );
sysctl( mib, 2, rstring, &len, NULL, 0 );
NSLog(@"%s", rstring );
free( rstring );
rstring = NULL;

Sourced from here . 来自这里

我不确定是否有通过Cocoa获取它的确切方法,但你可以使用NSTask并通过shell获取它。


sysctl hw.model

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM