MaxOSXで設定を保存するにはNSUserDefaultsまたはCFPreferenceを使用します。 また、Windowsではレジストリを使用します。 下記はそれぞれについてのサンプルです。
CocoaではNSUserDefaultsを使用して設定を保存できます。 サンプルは以下の通りです。
#import <Cocoa/Cocoa.h> int score; score = 125; NSUserDefaults* userdefaults = [NSUserDefaults standardUserDefaults]; [userdefaults setInteger:score forKey:@"score"];
#import <Cocoa/Cocoa.h> int score; NSUserDefaults* userdefaults = [NSUserDefaults standardUserDefaults]; score = [userdefaults integerForKey:@"score"];
CocoaではNSUserDefaultsの変わりにCFPreferenceを使用して設定を保存できます。 こちらはObjectiveCだけでなくC/C++言語から使用できます。 サンプルは以下の通りです。
#include <CoreFoundation/CFPreferences.h>
CFStringRef application_name;
CFNumberRef value;
int score;
application_name = CFSTR("application_name"); // kCFPreferencesCurrentApplicationを設定するとデフォルトの名前が適用される
score = 125;
value = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &score);
CFPreferencesSetAppValue(CFSTR("score"), value, application_name);
CFRelease(value);
CFPreferencesAppSynchronize(application_name);
#include <CoreFoundation/CFPreferences.h>
CFStringRef application_name;
CFNumberRef value;
int score;
application_name = CFSTR("application_name"); // kCFPreferencesCurrentApplicationを設定するとデフォルトの名前が適用される
value = CFPreferencesCopyAppValue(CFSTR("score"), application_name);
if(value)
{
CFNumberGetValue(value, kCFNumberIntType, &score);
CFRelease(value);
}
Windowsではレジストリに設定値を保存できます。 下記のREGISTRYTESTの部分はアプリケーションで自由に設定できます。 通常はアプリケーション名などにします。
#include <tchar.h>
#include <windows.h>
int score;
score = 125;
result = RegCreateKeyEx(HKEY_CURRENT_USER, _T("SOFTWARE\\REGISTRYTEST"), 0, _T(""), REG_OPTION_NON_VOLATILE, KEY_CREATE_SUB_KEY | KEY_WRITE, NULL, &handle, NULL);
if(result == ERROR_SUCCESS)
{
RegSetValueEx(handle, _T("score"), 0, REG_DWORD, reinterpret_cast<CONST BYTE*>(&score), sizeof(DWORD));
RegCloseKey(handle);
}
#include <tchar.h>
#include <windows.h>
int score;
result = RegOpenKeyEx(HKEY_CURRENT_USER, _T("SOFTWARE\\REGISTRYTEST"), 0, KEY_READ, &handle);
if(result == ERROR_SUCCESS)
{
DWORD type;
DWORD size;
result = RegQueryValueEx(handle, _T("score"), NULL, &type, NULL, &size);
if((result == ERROR_SUCCESS) && (type == REG_DWORD))
{
RegQueryValueEx(handle, _T("score"), NULL, &type, reinterpret_cast<LPBYTE>(&score), &size);
}
RegCloseKey(handle);
}
前に戻る?