日付を表示したいのですが、作成したアプリが初めてビューで開かれました(今のところ、アプリ全体で唯一のビューです)。
ビューで日付を表示するには、どのようなオブジェクトを使用するのが最適ですか? また、どのように日付を取得するのですか?
日付を表示したいのですが、作成したアプリが初めてビューで開かれました(今のところ、アプリ全体で唯一のビューです)。
ビューで日付を表示するには、どのようなオブジェクトを使用するのが最適ですか? また、どのように日付を取得するのですか?
AppDelegate で:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
if(![[NSUserDefaults standardUserDefaults] objectForKey:@"firstOpenDate"])
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[[NSUserDefaults standardUserDefaults] setObject:[dateFormatter stringFromDate:[NSDate date]] forKey:@"firstOpenDate"];
}
NSLog(@"First Opened: %@",[[NSUserDefaults standardUserDefaults] objectForKey:@"firstOpenDate"]);
return YES;
}
setDateStyle:NSDateFormatterLongStyle
他の形式が必要な場合は、単に変更してください。どこからでも照会できますNSUserDefaults
。
ViewController.m 内
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hi. You first opened the app on" message:[[NSUserDefaults standardUserDefaults] objectForKey:@"firstOpenDate"] delegate:nil cancelButtonTitle:@"Thanks" otherButtonTitles:nil];
[alert show];
}
最初の起動時に、objectForKey を使用して日付をユーザーの既定値に保存したかどうかを確認します。そうでない場合は、今日の日付を保存します
[NSD日付]
setObject:forKey を使用してデフォルトを使用するには:
次に、保存された日付を読み取り、その日付から今日までの日数を比較するコードに入ります。NSCalendar メソッドのコンポーネント:fromDate:toDate:options を見てください。
Xcode で「Performing Calendar Calculations」を検索して、結果の章を読んでください。