我在我的 Objective-C 程序中遇到了一个令人困惑的问题。当我的程序进入后台时,我试图从 NSMutableArray 保存数据。我的 AppDelegate 中有一个名为 savedResults 的静态变量。视图控制器在我的程序的生命周期内操作这个变量并向它添加数据。我有一个逻辑条件来检查 savedResults 是否为空,如果不是,那么我需要保存数据。这是我的代码:
NSString *const kFileName = @"PCFData.bin";
//these are all my static variables..I have to initialize them to something so
//they can be used in other parts of my program with the keyword extern.
NSString *finalTermValue = @"";
NSString *finalClassValue = @"";
NSString *finalTermDescription = @"";
NSMutableArray *savedResults = nil;
@implementation PCFAppDelegate
@synthesize finalTermValue, finalClassValue, finalTermDescription, savedResults;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullPath = [docDir stringByAppendingFormat:@"/%@", kFileName];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:fullPath];
if (fileExists) {
savedResults = [NSKeyedUnarchiver unarchiveObjectWithFile:fullPath];
}
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
if (savedResults) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSUserDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *fullPath = [docDir stringByAppendingFormat:@"/%@", kFileName];
[NSKeyedArchiver archiveRootObject:savedResults toFile:fullPath];
}
}
我在 applicationDidEnterBackgroundMethod 中放了一个断点,看看发生了什么。我的程序从不进入 if 语句中的代码块,即使 savedResults 数组不为空。我也尝试过测试 if ([savedResults count] > 0) 并且即使它大于零它也不会进入块。这是 XCode 显示的变量的图片。如您所见,数组中有对象。 我有一种感觉 XCode 正在查看上面的数组声明,我将其设置为 nil 而不是实际变量。我如何区分这两者?任何帮助将不胜感激。谢谢!