Skip to content

iOS_tutorial

guoling edited this page Apr 24, 2024 · 6 revisions

MMKV for iOS/macOS

MMKV is an efficient, small, easy-to-use mobile key-value storage framework used in the WeChat application. It's currently available on both Android, iOS/macOS, Windows and POSIX.

Tutorial

You can use MMKV as you go. All changes are saved immediately, no synchronize calls are needed.

Configuration

  • Setup MMKV on App startup, in your -[MyApp application: didFinishLaunchingWithOptions:], add these lines:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        // init MMKV in the main thread
        [MMKV initializeMMKV:nil];
    
        //...
        return YES;
    }
  • If multi-process accessing is needed(between the App and extensions), you need to set the group directory on MMKV initialization:

    NSString *myGroupID = @"group.company.mmkv";
    // the group dir that can be accessed by App & extensions
    NSString *groupDir = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:myGroupID].path;
    [MMKV initializeMMKV:nil groupDir:groupDir logLevel:MMKVLogInfo];

    Notice: When using MMKV in AppExtension or WatchExtension, you should link MMKV to your target by dynamic linking(for details, check the setup again).

CRUD Operations

  • MMKV has a default instance, which could be used directly:

    MMKV *mmkv = [MMKV defaultMMKV];
    
    [mmkv setBool:YES forKey:@"bool"];
    NSLog(@"bool:%d", [mmkv getBoolForKey:@"bool"]);
    
    [mmkv setInt32:-1024 forKey:@"int32"];
    NSLog(@"int32:%d", [mmkv getInt32ForKey:@"int32"]);
    
    [mmkv setInt64:std::numeric_limits<int64_t>::min() forKey:@"int64"];
    NSLog(@"int64:%lld", [mmkv getInt64ForKey:@"int64"]);
    
    [mmkv setFloat:-3.1415926 forKey:@"float"];
    NSLog(@"float:%f", [mmkv getFloatForKey:@"float"]);
    
    [mmkv setString:@"hello, mmkv" forKey:@"string"];
    NSLog(@"string:%@", [mmkv getStringForKey:@"string"]);
    
    [mmkv setDateorKey:@"date"];
    NSLog(@"date:%@", [mmkv getDateForKey:@"date"]);
    
    NSData *data = [@"hello, mmkv again and again" dataUsingEncoding:NSUTF8StringEncoding];
    [mmkv setDataForKey:@"data"];
    data = [mmkv getDataForKey:@"data"];

NSLog(@"data:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);

NSDictionary *dic = @{@"key1" : @"value1",
                      @"key2" : @(2)};
[mmkv setObject:dic forKey:@"dictionary"];
dic = [mmkv getObjectOfClass:[NSDictionary class] forKey:@"dictionary"];
NSLog(@"dictionary:%@", dic);

```

As you can see, MMKV is quite simple to use.

  • Deleting, Querying & Enumerating:

    MMKV *mmkv = [MMKV defaultMMKV];
    
    [mmkv removeValueForKey:@"bool"];
    [mmkv removeValuesForKeys:@[@"int32", @"int64"]];
    
    BOOL hasBool = [mmkv containsKey:@"bool"];
        
    [mmkv enumerateKeys:^(NSString *key, BOOL *stop) {
        if ([key isEqualToString:@"string"]) {
            NSString *value = [mmkv getStringForKey:key];
            NSLog(@"%@ = %@", key, value);
            *stop = YES;
        }
    }];
    
    // delete everything
    [mmkv clearAll];
  • If different modules/logics need isolated storage, you can also create your own MMKV instance separately:

    MMKV *mmkv = [MMKV mmkvWithID:@"MyID"];
    [mmkv setBool:YES forKey:@"bool"];
  • If multi-process accessing is needed(between the App and extensions), you need to set the group directory on MMKV initialization as written before. Then you can get one by passing MMKVMultiProcess:

    MMKV *mmkv = [MMKV mmkvWithID:@"MyMultiID" mode:MMKVMultiProcess];
    [mmkv setBool:YES forKey:@"bool"];

Supported Types

  • C/C++ Primitive Types:
    • bool, int32, int64, uint32, uint64, float, double
  • Objective-C Class:
    • NSString, NSData, NSDate
  • Any Class that implements <NSCoding> protocol.

Import from NSUserDefaults

  • MMKV provides -[MMKV migrateFromUserDefaultsDictionaryRepresentation:],you can migrate from NSUserDefaults with one line of code.

    auto userDefault = [[NSUserDefaults alloc] initWithSuiteName:@"myDefault"];
    auto mmkv = [MMKV mmkvWithID:@"testImportNSUserDefaults"];
    [mmkv migrateFromUserDefaultsDictionaryRepresentation: userDefault.dictionaryRepresentation];
    // delete keys & values from userDefault when you're done

What's Next

Clone this wiki locally