2012-07-23 169 views
0

在我的應用程序中,我有一些顏色設置,字體設置和包含特定於應用程序的對象的字典(這些對象是具有屬性的類,這些對於應用程序是私有的)。顏色設置和字體設置是應用程序的公共設置。我想將它們保存到NSUserDefaults的,但它會顯示任何字體或顏色正常,所以我用這行代碼將UIColor,UIFont和NSDictionary保存到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保存它們。爲了使上述代碼正常工作,我需要在應用程序項目中添加一個「設置包」文件。這會導致應用程序在設備/系統設置面板中輸入一個條目。它是空的,因爲我沒有在設置包文件中設置任何應用程序配置細節。

我該如何解決這個問題?

+0

你爲什麼不只是讓你要保存的屬性的自定義對象,然後存檔/取消存檔嗎? – Dustin 2012-07-23 17:37:46

回答

1

定製支持對象

@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; 
} 
+0

感謝您的回覆。問題是......我將如何保存這些默認設置?用戶需要一種方法來將設置設置爲默認狀態,如果他弄糟了。 :) – CodeWeed 2012-07-23 17:45:33

+1

您可以在應用程序的開頭將此對象寫入文件,然後讓用戶編輯它。如果他搞砸了,你可以使用'objectName = [/ * unarchive method * /]'來取回未經編輯的版本。 – Dustin 2012-07-23 17:48:25

+0

謝謝,我會這樣做的,但我覺得這是一種骯髒的方式來做到這一點。 :-) – CodeWeed 2012-07-23 18:06:00