objective-c - 将 UIColor、UIFont 和 NSDictionary 保存到 NSUserDefaults

标签 objective-c ios cocoa ios5 nsuserdefaults

在我的应用程序中,我有一些颜色设置、字体设置和包含应用程序特定对象的字典(这些对象是具有属性的类,这些属性是应用程序私有(private)的)。颜色设置和字体设置是应用程序的公共(public)设置。我想将它们保存到 NSUserDefaults 但它会正确显示任何字体或颜色,所以我使用这行代码保存它们

// reading the value
NSData *foregroundcolorData = [[NSUserDefaults standardUserDefaults] objectForKey:@"foregroundcolor"];
UIColor *foregndcolor = [NSKeyedUnarchiver unarchiveObjectWithData:foregroundcolorData];

// setting the default values
NSData *foregndcolorData = [NSKeyedArchiver archivedDataWithRootObject:[UIColor blackColor]];
    [[NSUserDefaults standardUserDefaults] setObject:foregndcolorData forKey:@"foregroundcolor"];

// saving the changes, by putting everything in a dictionary called "preferences"
[[NSUserDefaults standardUserDefaults] registerDefaults:preferences];
[[NSUserDefaults standardUserDefaults] synchronize];

我决定将所有设置都放在应用程序 UI 中。为了使上面的代码正常工作,我需要向应用程序项目添加一个“设置 bundle ”文件。这会导致应用程序在设备/系统设置面板中放置一个条目。它是空的,因为我没有在设置捆绑文件中设置任何应用程序配置详细信息。

如何解决这个问题?

最佳答案

自定义持有者对象

@interface HolderObject : NSObject

@property (strong, nonatomic) UIColor *xColor;
@property (strong, nonatomic) UIFont *xFont;

@end

@implementation PTextHolder

@synthesize xColor, xFont;

- (void)encodeWithCoder:(NSCoder *)encoder 
{
    [encoder encodeObject:xColor forKey:@"xColor"];
    [encoder encodeObject:xFont forKey:@"xFont"];
}

- (id)initWithCoder:(NSCoder *)decoder 
{
    if (self = [super init]) 
    {
        self.xColor = [decoder decodeObjectForKey:@"xColor"];
        self.xFont = [decoder decodeObjectForKey:@"xFont"];
    }
    return self;
}

关于objective-c - 将 UIColor、UIFont 和 NSDictionary 保存到 NSUserDefaults,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11617295/

相关文章:

iphone - Objective-C 中的 NSRange 有问题吗?

ios - 类的 Xcode 10.0 用户搜索路径(已弃用)

objective-c - 任何一对多对多谓词

cocoa - 使用 NSColorWell 的基于 View 的表格 View

ios - 带分页的UITableView,每个cell是一个UIScrollView

ios - 当其任何 subview 设置为隐藏时通知父 View

ios - 哪个是存储数据(coredata 或 sql)的最佳解决方案?

ios - 导航 UIBarButtonItem 在设备上的外观不同

objective-c - 来自两个 NSImage 的 NSImage

objective-c - ExtAudioFileRead 在 iOS 5 中给出不同的结果