2013-08-27 80 views
0

我现在有这个功能,init的我的用户的默认值:结构包裹在NSValue内存问题

+ (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]; 
} 

我得到一个OBJ-C异常断点在“CFRetain”,而注册的默认值。 在使用NSValue之前,一切都很好,所以我确信这是与内存有关的东西。我知道该结构在本地函数堆栈上是有效的,所以我想知道这是否是问题? NSValue是否复制它获取指针的值?

我应该在堆上创建结构吗?

谢谢!

回答

2

您不能将NSValue直接存储到用户默认值中,因为它由plist支持。因此,字典中的所有条目都需要在plist中存储有效。考虑将值存储为基本整数或将结构编码为数据或字符串格式。

+0

完美,谢谢!想想我会用NSData版本去。 – guitarflow