Search code examples
iosobjective-cnsarraykeychainitemwrapper

Store an NSArray into a KeychainItemWrapper


I have to store an NSArray (which contains NSString and BOOL) into a KeychainItemWrapper to re use it in another ViewController, and to keep it in memory even if the app is closed.

I've already see at this question but it won't help me, because I can't find the SBJsonWriter files.

Can anyone could help me please ?

Thanks a lots.

Have a good day !


Solution

  • SBJsonWriter is a 3rd party JSON library popular years back, now iOS has this built in.

    Serialize the data as JSON using the native NSJSONSerialization, and then write it to the keychain (assuming kSecValueData, which is encrypted):

    NSArray* array = ...;
    
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:array options:0 error:nil];
    NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    [keychainItem setObject:jsonString forKey:(__bridge id)kSecValueData];
    

    To read the data back to an NSArray:

    NSString* jsonString = [keychainItem objectForKey:(__bridge id)kSecValueData];
    NSArray* array = nil;
    
    if(jsonString.length > 0)
    {
        id jsonObject = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
    
        //  Type check because the JSON serializer can return an array or dictionary
        if([jsonObject isKindOfClass:[NSArray class]])
            array = jsonObject;
    }
    
    //  use your array variable here, it may be nil