2012-07-13 89 views
0

當調用appLaunched時,我有一個NSMutableArray與NSUserDefaults一起保存,但數組返回null時,如果由其他函數調用,則返回數組中的內容。任何人都知道發生了什麼?NSArray從NSNotificationCenter調用時返回爲空

- (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 

回答

0

您沒有同步您的NSUserDefaults。 每當您使用[[NSUserDefaults standardUserDefaults] setObject:someObject forKey:@"someKey"];時,您都必須使用[[NSUserDefaults standardUserDefaults] synchronize];後綴。