从AppDelegate访问时,NSManagedObject会导致NSUnknownKeyException

时间:2011-12-04 06:45:56

标签: objective-c core-data nsmanagedobject

美好的一天。

在我的AppDelegate.h上

  

@property(非原子,保留)Config * AppConfig;

在我的AppDelegate.m中,我可以毫无问题地访问它。

UIAlertView *alert = 
[[UIAlertView alloc] initWithTitle:@"Settings Saved" 
                           message:[NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@",
                                    AppConfig.Username, AppConfig.Password, 
                                    AppConfig.Server, AppConfig.LastRefNo,
                                    AppConfig.LastSync]
                          delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];

AppConfig正在AppDelegate中填充,如下所示

- (void)GetSettings
{
    // Define our table/entity to use  
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Config" inManagedObjectContext:managedObjectContext];   

    // Setup the fetch request  
    NSFetchRequest *request = [[NSFetchRequest alloc] init];  
    [request setEntity:entity];   

    // Define how we will sort the records  
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"Username" ascending:NO];  
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];  
    [request setSortDescriptors:sortDescriptors];  
    [sortDescriptor release];   

    // Fetch the records and handle an error  
    NSError *error;  
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];   

    if (mutableFetchResults != nil && [mutableFetchResults count] > 0) {  
        // Save our fetched data
        AppConfig = [mutableFetchResults objectAtIndex:0];
    }  
    else 
    {
        AppConfig = nil;
    }

    [mutableFetchResults release];  
    [request release];  
}

如果我尝试通过此

从另一个ViewController访问AppConfig
- (void)loadAccount
{
    SpotlightAppDelegate *_appDelegate = (SpotlightAppDelegate *) [[UIApplication sharedApplication] delegate];

    txtUsername.text = [_appDelegate.AppConfig valueForKey:@"Username"];
    txtPassword.text = [_appDelegate.AppConfig valueForKey:@"Password"];
}

第2行抛出NSUnknownKeyException。

提前致谢。

1 个答案:

答案 0 :(得分:0)

好的,我休息了一段时间后发现了它: - )

我应该在AppConfig上调用retain。