Objective-C プログラムで紛らわしい問題が発生しています。プログラムがバックグラウンドに入ったときに、NSMutableArray からデータを保存しようとしています。AppDelegate に savedResults という静的変数があります。ビュー コントローラーはこの変数を操作し、プログラムの有効期間中にデータを追加します。savedResults が null かどうかをチェックする論理条件があり、そうでない場合はデータを保存する必要があります。これが私のコードです:
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 にブレークポイントを設定しました。savedResults 配列が null でない場合でも、私のプログラムは if ステートメント内にコード ブロックを入力しません。if ([savedResults count] > 0) もテストしてみましたが、ゼロより大きい場合でもブロックに入りません。これは、XCode が表示している変数の図です。ご覧のとおり、配列には ARE オブジェクトがあります。
XCode は、実際の変数ではなく nil に設定した上記の配列宣言を見ているように感じます。この 2 つをどのように区別すればよいでしょうか。どんな助けでも大歓迎です。ありがとう!