2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

React Native で NSUserDefaults を扱う (iOS)

Last updated at Posted at 2020-06-27

はじめに

React Native アプリで自分でネイティブモジュールを書くような開発をしているときに、ネイティブ側の設定値を操作したいことがあるかもしれません。
iOS のNSUserDefaults の値を参照・更新したいという時に、React Native の Settings を使えばそれができるよという話です。

検証環境

  • React Native v0.62.2

NSUserDefaults とは

iOS でちょっとした設定値のようなデータを永続化するための仕組みです。
key-value のペアでデータを端末に保存できます。

補足

React Native では AsyncStorage (@react-native-community/async-storage) を使うことが多いため、開発者がNSUserDefaults を使ったコードを書く機会はあまりないでしょう。

Settings

React Native の SettingsNSUserDefaults のラッパーです。
使い方を簡単に紹介します。

JavaScript 側

import

import { Settings } from "react-native";

値の書き込み

const yourKey = 'isEnabledSomeFunc';
const yourValue = true;
Settings.set({yourKey: yourValue});

値の取得

Settings.get(yourKey); // => 1

boolean の値を取得しようとするとnumber で返ってきました。
型の変換については開発者側で気を付けるのが良さそうです。
(React Native のコードを読めば処理の詳細が分かるのですが、今回はスキップします)

!!Settings.get(yourKey); // => true

ネイティブ側

値の取得

動作確認のため、ネイティブ側でもデバッグしてみます。
Objective-C だとこう書けます。

BOOL value = [[NSUserDefaults standardUserDefaults] boolForKey:@"isEnabledSomeFunc"];
NSLog(@"%@", (value) ? @"YES" : @"NO"); // "YES"

さいごに

React Native のSettings を使うことで、iOS のNSUserDefaults を叩くだけのネイティブモジュールを自分で作らずに済みました。

なお Settings には watchKeys というメソッドも用意されていて、ネイティブ側で NSUserDefaults の指定したキーの値が変わった際の変更を購読することもできるようです。上手く使うと便利かもしれないですね。

参考

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?