Question

I currently have this function which init's my user defaults:

+ (void)initialize
{
    // Create a dictionary to hold the default user preference values
    NSMutableDictionary *defaultValues = [NSMutableDictionary dictionary];

    // Put defaults in the dictionary
    [defaultValues setObject:@(YES) forKey:@"pref key 1"];
    ... (further inits)

    MyCStruct struct;
    struct.width = struct.height = 0;
    struct.frameDuration = struct.frameTimeScale = 0;

    NSValue* structDefaultValue = [NSValue value:&struct 
                                    withObjCType:@encode(MyCStruct)];
    [defaultValues setObject:structDefaultValue 
                      forKey:@"myPrefKey"];

    // Register the dictionary of defaults
    [[NSUserDefaults standardUserDefaults] registerDefaults: defaultValues];
}

I get an Obj-C exception breakpoint in "CFRetain" while registering the defaults. Everything was fine BEFORE I used the NSValue, so I'm sure that's something memory related. I know that the struct is just valid on the local function stack, so I'm wondering if this is the problem? Does NSValue copy the value it gets a pointer to?

Should I create the struct on the heap?

Thanks!

Was it helpful?

Solution

You can't store an NSValue direct into user defaults because it's backed by a plist. So all of the entries in the dictionary need to be valid for storage in a plist. Consider storing the values as basic integers or encoding the struct to data or a string format.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top