简体   繁体   English

将第三方库自定义对象保存到NSUSerDefault

[英]Save Third party Library Custom Object to NSUSerDefault

So,I am using the AFPhotoEditorController and there is property of it named as AFPhotoeditorSession that stores and tracks all user action.THis session class is custom object that inherits from NSObject,I have googled about how to save custom objects in NSUser Defaults and came to know that We can save that class if that class conforms to protocol NSCoding ,I don't know that whether I can change this class,Because it is only.h file that I have in my custom framework of AviarySDk. 因此,我使用的是AFPhotoEditorController,它的属性名为AFPhotoeditorSession,用于存储和跟踪所有用户操作。该会话类是继承自NSObject的自定义对象,我在Google上搜索了如何在NSUser Defaults中保存自定义对象,我知道如果该类符合协议NSCoding,那么我们可以保存该类,我不知道是否可以更改该类,因为它是AviarySDk的自定义框架中仅有的.h文件。

    NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:
   [self.sessions objectAtIndex:0]]; // self.session an array of one object of AFPhotoeditorSession
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:myEncodedObject forKey:@"myEncodedObjectKey"];
        [defaults synchronize];
        NSData *data1 = [defaults objectForKey:@"myEncodedObjectKey"];
        AFPhotoEditorSession *obj = (AFPhotoEditorSession *)[NSKeyedUnarchiver unarchiveObjectWithData: data1];
        NSLog(@"%@",obj);

I am getting error like : 我收到如下错误:

*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<AFPhotoEditorSession 0x1c5fa0f0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key modified.'

And you can check the AFPhotoEditor Session class at PhotoEditorSession 你可以检查在AFPhotoEditor Session类PhotoEditorSession

您可以通过声明并定义一个符合该协议并实现必要方法的类别,使该类符合NSCoding

Actually creating your own category means that you will have to have it compliant with that object as new ivars are added or changed, forever. 实际上,创建自己的类别意味着随着永久添加或更改新的ivars,您将必须使其与该对象兼容。

The right way to do this is to determine exactly what you would need to recreate an object of that class - the core values - then create keys and values for each and put them into a dictionary. 正确的方法是确切确定重新创建该类的对象(核心值)所需的内容,然后为每个对象创建键和值并将它们放入字典中。 Put the dictionaries into your user defaults. 将字典放入您的用户默认设置中。 When you want to retrieve the values, pull out a dictionary, use those values to instantiate the objects. 当您要检索值时,请拔出字典,使用这些值实例化对象。

The other option is to ask the author of AFPhotoeditor to do it, or do it yourself, and send him a pull request. 另一种选择是让AFPhotoeditor的作者自己执行,或自己执行,然后向他发送请求请求。 But if you do it as a add on, you will have to update your category everytime the original framework changes. 但是,如果您将其作为附加组件使用,则每次原始框架更改时,您都必须更新类别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM