2013-08-27 79 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