SpokaneDude
SpokaneDude

Reputation: 4974

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?

Upvotes: 1

Views: 289

Answers (1)

rmaddy
rmaddy

Reputation: 318814

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

Upvotes: 3

Related Questions