NSUserDefaults数据最初没有出现?

时间:2011-03-19 00:02:37

标签: iphone objective-c nsmutablearray

当我启动我的应用程序时,它会进入homeview,并且不会显示NSUserDefaults中保存的任何现有调色板。但是当我点击“新调色板”按钮并返回时,它会显示新的和所有现有按钮。无法深究这一点。任何帮助表示赞赏。

app delegate.h:

@interface palettesAppDelegate : NSObject <UIApplicationDelegate> {
 NSMutableArray *colourPalettesContainer;
    NSUserDefaults *prefs;
}
@property (assign, readwrite) NSUserDefaults *prefs;
@property (assign, readwrite) NSMutableArray *colourPalettesContainer;
@end

app delegate.m:

#import "palettesAppDelegate.h"

@implementation palettesAppDelegate

@synthesize colourPalettesContainer, prefs;

- (void)dealloc {
    [colourPalettesContainer release];
    [super dealloc];
}


@end

Homeview.h:

#import <UIKit/UIKit.h>
#import "HandlingPalettes.h"

@interface HomeView : UIViewController {

    HandlingPalettes *handlingPalettes;

}


@end

Homeview.m:

#import "HomeView.h"
#import <QuartzCore/QuartzCore.h>


@implementation HomeView


- (void)viewDidLoad {
    [super viewDidLoad];
palettesAppDelegate *dataCenter = (palettesAppDelegate *)[[UIApplication sharedApplication] delegate];

dataCenter.prefs = [NSUserDefaults standardUserDefaults];
dataCenter.colourPalettesContainer = [dataCenter.prefs objectForKey:@"palettes"];

handlingPalettes = [[HandlingPalettes alloc] init];

    [handlingPalettes newPalette];

}

-(void)viewWillAppear:(BOOL)animated {


    NSLog(@"view will appear: %i", [dataCenter.colourPalettesContainer count]);
    int numberOfExisting = [dataCenter.colourPalettesContainer count];

}

- (void)dealloc {
    [handlingPalettes release];
    [super dealloc];
}


@end

HandlingPalettes.h:

#import <UIKit/UIKit.h>

@interface HandlingPalettes : UIViewController {

}


-(void)newPalette;



@end

HandlingPalettes.m:

#import "HandlingPalettes.h"
#import "HomeView.h"
#import "palettesAppDelegate.h"



@implementation HandlingPalettes


-(void)newPalette {

    palettesAppDelegate *dataCenter = (palettesAppDelegate *)[[UIApplication sharedApplication] delegate];

    //If this is the first palette
    if (dataCenter.colourPalettesContainer == nil) {
    dataCenter.colourPalettesContainer = [[NSMutableArray alloc] init];
    }
    //Add a new palette

        [dataCenter.colourPalettesContainer addObject:@"Test1", @"Test2", nil];


    NSLog(@"Handling:    %i", [dataCenter.colourPalettesContainer count]);

    [dataCenter.prefs setObject:dataCenter.colourPalettesContainer forKey:@"palettes"];
[dataCenter.prefs synchronize];
}
- (void)dealloc {
   [super dealloc];
}


@end

1 个答案:

答案 0 :(得分:1)

问题是,当您加载应用程序并调用您的应用程序委托时,您不会从NSUserDefaults恢复其内容。如果它是零,你只是创建它,但这并不能解决问题。您应该使用应用程序中的值填充colourPalettesContainer数组:didFinishLaunchingWithOptions:method。

此外,Kalle的上述评论是相关的;你不应该像那样使用你的app委托。最好的方法是将IMHO包装在一个自定义类中,该类负责在首次启动时存储默认值,管理版本控制,提供强类型接口,并且如果需要可以是子类。