2012-10-24 43 views

回答

2

在你的類AppDelegate中。你可以這樣做:

//Application did launch 
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    int count = [[NSUserDefaults standardUserDefaults] integerForKey:@"LaunchCount"]; 
    if(count < 0) count = 0; 
    [[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:@"LaunchCount"]; 
} 

//The application was in background and become active 
- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 
    int count = [[NSUserDefaults standardUserDefaults] integerForKey:@"LaunchCount"]; 
    if(count < 0) count = 0; 
    [[NSUserDefaults standardUserDefaults] setInteger:count+1 forKey:@"LaunchCount"]; 
} 
+0

10x工作完美! – Sosily

+0

@Ashbay你可以把它放在viewDidLoad下面嗎? –

3
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ 
    //add 1 
} 

 image

圖像從http://www.cocoanetics.com/2010/07/understanding-ios-4-backgrounding-and-delegate-messaging/

+0

他應該重寫didBecomeActive方法: - (無效)applicationDidBecomeActive:(UIApplication *)應用程序 – Ashbay

+1

在我對此問題的理解中,OP想知道應用程序啓動/初始化了多少次。當應用程序從不活動狀態轉換到活動狀態時,例如應用程序處於活動狀態,然後發生中斷(例如電話呼叫),將調用applicationDidBecomeActive',如果用戶沒有接聽電話,則會調用applicationDidBecomeActive'。 – janusbalatbat

+0

是的,你說得對。這是我沒有想到的。 – Ashbay

0

是,使用是NSUserDefaults的一個簡單的解決方案。

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary  *)launchOptions{ 
    // Get the NSUserDefault number here, if not available, create a new. 
} 

如果你想它來跟蹤它是從後臺重新開始的時刻,看看:

-(void) applicationWillEnterForeground:(UIApplication*)application 

嘗試是這樣的:

// Get the number of starts: 
NSNumber *starts = [[NSUserDefaults standardUserDefaults] objectForKey:@"starts"]; 

// increase by one 
NSNumber *number = [NSNumber numberWithInt:([starts intValue] + 1)]; 

// store the number of starts 
[[NSUserDefaults standardUserDefaults] setObject:starts forKey:@"starts"]; 
相關問題