*第12回目 Cocoa、Windowsで設定保存 [#w67e5ad5]
 MaxOSXで設定を保存するにはNSUserDefaultsまたはCFPreferenceを使用します。
 また、Windowsではレジストリを使用します。
 下記はそれぞれについてのサンプルです。
**NSUserDefaults [#p974d919]
 CocoaではNSUserDefaultsを使用して設定を保存できます。
 サンプルは以下の通りです。
***int値を書き込む [#o0f1d122]
 #import <Cocoa/Cocoa.h>
 int score;
 score = 125;
 NSUserDefaults* userdefaults = [NSUserDefaults standardUserDefaults];
 [userdefaults setInteger:score forKey:@"score"];
***int値を読み出す [#y51c254f]
 #import <Cocoa/Cocoa.h>
 int score;
 NSUserDefaults* userdefaults = [NSUserDefaults standardUserDefaults];
 score = [userdefaults integerForKey:@"score"];
**CFPreference [#b3f12ab2]
 CocoaではNSUserDefaultsの変わりにCFPreferenceを使用して設定を保存できます。
 こちらはObjectiveCだけでなくC/C++言語から使用できます。
 サンプルは以下の通りです。
***int値を書き込む [#n816e9b2]
 #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);
***int値を読み出す [#add24835]
 #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);
 }
**レジストリ [#n075ba1a]
 Windowsではレジストリに設定値を保存できます。
 下記のREGISTRYTESTの部分はアプリケーションで自由に設定できます。
 通常はアプリケーション名などにします。
***int値を書き込む [#o8940cfd]
 #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);
 }
***int値を読み出す [#w4887be1]
 #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);
 }

[[前に戻る>プログラミング]]

トップ   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS