▼iPhoneプログラミングメモ▼
プリファレンスの読み書き

プリファレンスの読み書きを行うプログラムを作成する。


ソースコードの記述
PreferenceEx.h
#import <UIKit/UIKit.h>

//PreferenceExの宣言
@interface PreferenceEx : UIViewController <UITextFieldDelegate> {
    UITextField* _textField;
}
@end

PreferenceEx.m
#import "PreferenceEx.h"

#define BTN_WRITE 0
#define BTN_READ  1

//PreferenceExの実装
@implementation PreferenceEx

//テキストフィールドの生成
- (UITextField*)makeTextField:(CGRect)rect text:(NSString*)text {
    UITextField* textField=[[[UITextField alloc] init] autorelease];
    [textField setText:text];
    [textField setFrame:rect];
    [textField setReturnKeyType:UIReturnKeyDone];
    [textField setBackgroundColor:[UIColor whiteColor]];
    [textField setBorderStyle:UITextBorderStyleRoundedRect];
    [textField setDelegate:self];
    return textField;
}

//テキストボタンの生成
- (UIButton*)makeButton:(CGRect)rect text:(NSString*)text tag:(int)tag {
    UIButton* button=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:rect];
    [button setTitle:text forState:UIControlStateNormal];
    [button setTag:tag];
    [button addTarget:self action:@selector(clickButton:) 
        forControlEvents:UIControlEventTouchUpInside];
    return button;
}

//初期化
- (void)viewDidLoad {
    [super viewDidLoad];
        
    //テキストフィールドの生成
    _textField=[[self makeTextField:CGRectMake(0,0,300,32) 
        text:@""] retain];
    [self.view addSubview:_textField];
        
    //書き込みボタンの生成
    UIButton* btnWrite=[self makeButton:CGRectMake(0,50,90,40) 
        text:@"書き込み" tag:BTN_WRITE];
    [self.view addSubview:btnWrite];

    //読み込みボタンの生成
    UIButton* btnRead=[self makeButton:CGRectMake(100,50,90,40) 
        text:@"読み込み" tag:BTN_READ];
    [self.view addSubview:btnRead];
}

//メモリ解放
- (void)dealloc {
    [_textField release];
    [super dealloc];
}

//テキストフィールドのリターン時に呼ばれる
- (BOOL)textFieldShouldReturn:(UITextField*)sender {
    [sender resignFirstResponder];
    return YES;
}

//ボタンクリック時に呼ばれる
- (IBAction)clickButton:(UIButton*)sender {
    if (sender.tag==BTN_WRITE) {
        //プリファレンスの書き込み
        NSUserDefaults* pref=[NSUserDefaults standardUserDefaults];
        [pref setObject:_textField.text forKey:@"text"];
        [pref synchronize];
    } else if (sender.tag==BTN_READ) {
        //プリファレンスの読み込み
        NSUserDefaults* pref=[NSUserDefaults standardUserDefaults];
        _textField.text=[pref stringForKey:@"text"];
    }
}

//画面を端末の向きにあわせて回転
- (BOOL)shouldAutorotateToInterfaceOrientation:
    (UIInterfaceOrientation)orientation {
    return YES;
}
@end



−戻る−