0

我有一个使用 NSUserDefaults 保存的 NSMutableArray,当调用 appLaunched 时,该数组返回 null,但是当被任何其他函数调用时,它返回数组中的内容。有人知道发生了什么吗?

- (id)init
 {
[super init];
theArray = [[NSMutableArray alloc] init];
theArray = [[NSUserDefaults standardUserDefaults] objectForKey:@"TheArray"];
if(!theArray) {
    theArray = [[NSMutableArray alloc] init];
} else {
    theArray = [[NSMutableArray alloc] initWithArray:theArray];
};

// NSLog(@"%@", theArray);
[[NSUserDefaults standardUserDefaults] setObject:theArray forKey:@"TheArray"];
// NSLog(@"Is saving");

return self;
}


 -(IBAction)addNewProcess:(id)sender
 {
     NSString *newProcess = [theField stringValue];
     [theArray addObject:newProcess];
     [theField setStringValue:@""];
     NSLog(@"%@", theArray);
     [theTable reloadData];

 }

 -(IBAction)removeProcess:(id)sender
 {
     int listRow = [theTable selectedRow];
     NSLog(@"%d", listRow);
     if (listRow < 0) return;
     [theArray removeObjectAtIndex:listRow];
     [theTable reloadData];
 }

 -(IBAction)save:(id)sender
 {
     NSLog(@"%@", theArray);
     int count = [theArray count];
     NSLog(@"%i", count);
     [[NSUserDefaults standardUserDefaults] setObject:theArray forKey:@"TheArray"];
     NSLog(@"Is saving");
  }

 - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
 {
     return [theArray count];
 }

 - (id)tableView:(NSTableView *)tableView 
 objectValueForTableColumn:(NSTableColumn *)tableColumn 
             row:(NSInteger)row
 {
     return [theArray objectAtIndex:row];
 }

 - (void)tableView:(NSTableView *)tableView 
    setObjectValue:(id)object 
    forTableColumn:(NSTableColumn *)tableColumn 
               row:(NSInteger)row
 {
     [theArray replaceObjectAtIndex:row
                               withObject:object];
 }

 -(void)appLaunched:(NSNotification *)note
 {
     NSLog(@"%@", theArray);

 }


 @end
4

1 回答 1

0

你没有同步你的 NSUserDefaults。每次使用[[NSUserDefaults standardUserDefaults] setObject:someObject forKey:@"someKey"];时都必须使用[[NSUserDefaults standardUserDefaults] synchronize];后记。

于 2013-12-14T19:14:03.200 回答