Search code examples
objective-cnsmutablearrayios8.1nsubiquitouskeyvaluestore

Unable to set array in NSUbiquitousKeyValueStore


This is my Obj-C code:

    NSMutableArray *staffNamesArray = [[[NSUbiquitousKeyValueStore defaultStore] arrayForKey:@"staffNamesArray"] mutableCopy];

    NSInteger indexSelected = [oStaffPickerView selectedRowInComponent:0];
    [staffNamesArray replaceObjectAtIndex:indexSelected withObject:textField.text];

    [[NSUbiquitousKeyValueStore defaultStore] setArray: staffNamesArray forKey:@"staffNamesArray"];  //  save it to the cloud
    [[NSUbiquitousKeyValueStore defaultStore] synchronize];

IndexSelected is 0; textfield.text = @"Kellie".

For some reason, staffNamesArray never gets set. Why?


Solution

  • The most likely issue is this line:

    NSMutableArray *staffNamesArray = [[[NSUbiquitousKeyValueStore defaultStore] arrayForKey:@"staffNamesArray"] mutableCopy];
    

    This will result in staffNamesArray being nil if there is no data. You need to check for this and create an array as needed:

    NSMutableArray *staffNamesArray = [[[NSUbiquitousKeyValueStore defaultStore] arrayForKey:@"staffNamesArray"] mutableCopy];
    if (!staffNamesArray) {
        staffNamesArray = [NSMutableArray array];
    }
    
    // and the rest of your code