从NSNotificationCenter调用NSArray时返回null

时间:2012-07-13 02:32:28

标签: cocoa nsmutablearray nstableview nsnotificationcenter

我有一个NSMutableArray与NSUserDefaults一起保存,当调用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

1 个答案:

答案 0 :(得分:0)

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