delegateでの呼び出し

NSUserDefaultsで読み出したデータをdelegateで呼び出す処理。

読んだデータはNSMutableDictionaryに入れる。

  • xxxxAppDelegate.h


#define CONFIG @"conf"
    : chomp
@interface xxxxAppDelegate : NSObject {
    : chomp
    NSMutableDictionary *config; // 設定
}
@property (nonatomic, assign) NSMutableDictionary *config;
    : chomp

  • xxxxAppDelegate.m


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    : chomp
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    config = [ [NSMutableDictionary alloc] init];
    [config setDictionary:[defaults dictionaryForKey:CONFIG] ];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:config forKey:CONFIG];
    [defaults synchronize];
}
- (void)dealloc {
    : chomp
    [config release];
    : chomp
}



あとは使う側でdelegate経由で値取得。

xxxxAppDelegate * delegate = (xxxxAppDelegate *)[[UIApplication sharedApplication] delegate];
NSString val = [ delegate.config objectForKey:@"key1"] ;


書籍を見ながらコードを書いたけどうまく動かなかったです。

@property (nonatomic, assign)の指定が必須、ということは書いてあったけどどういうことなのか書いてなくて・・・。

  • propertyを宣言する→アクセサ経由でアクセスするようになる。self.somethingはアクセサ経由。
  • synthesizeを宣言する→アクセサ(setter, getter)のコードを自分で書かなくても良くなる。
  • assign→自動でallocしない。ポインタ型の場合は明示的にalloc/releaseしないと残念なことになる。
  • retain→自動でallocする。release処理必須。
  • nonatomic→atomicがデフォルト値で、スレッドセーフ。nonatomicにするとロックしなくなる。

ということらしい。