iOS_tutorial

guoling edited this page Sep 18, 2018 · 1 revision

MMKV for iOS

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

Turtorial

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

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 setObject:@"hello, mmkv" forKey:@"string"];
    NSLog(@"string:%@", [mmkv getObjectOfClass:NSString.class forKey:@"string"]);
    
    [mmkv setObject:[NSDate date] forKey:@"date"];
    NSLog(@"date:%@", [mmkv getObjectOfClass:NSDate.class forKey:@"date"]);
    
    NSData *data = [@"hello, mmkv again and again" dataUsingEncoding:NSUTF8StringEncoding];
    [mmkv setObject:data forKey:@"data"];
    data = [mmkv getObjectOfClass:NSData.class forKey:@"data"];

NSLog(@"data:%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); ``` As you can see,MMKV is quite simple to use.

  • If different modules/logics need isolated storage, you can also create your own MMKV instance separately:

    MMKV *mmkv = [MMKV mmkvWithID:@"MyID"];
    [mmkv setBool:NO forKey:@"bool"];
  • 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 getObjectOfClass:NSString.class forKey:key];
            NSLog(@"%@ = %@", key, value);
            *stop = YES;
        }
    }];
    
    // delete everything
    [mmkv clearAll];

Supported Types

  • C/C++ Primitive Types:
    • bool, int32, int64, uint32, uint64, float, double
  • Objective-C Interfaces:
    • NSString, NSData, NSDate

What's Next

You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.