如何只运行一次代码?

Obj*_*rog 4 iphone xcode cocoa-touch objective-c

我正在开发一个iPhone应用程序,我想知道我是否只能运行一次代码段(换句话说:初始化代码,我希望它只在第一次运行时执行).这是我的代码,我在didFinishLaunchingwithOptions方法中执行它:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    

// Override point for customization after application launch.

// Add the tab bar controller's view to the window and display.
[self.window addSubview:tabBarController.view];
[self.tabBarController setSelectedIndex:2];
[self.window makeKeyAndVisible];

[self createPlist1];
[self createPlist2];
[self createPlist3];

return YES;
Run Code Online (Sandbox Code Playgroud)

}

我希望最后三条消息只在第一次运行时执行.我想我可以使用UserDefaults并在这些消息执行后设置一个键(在第一次运行时)并在每次运行时检查该键的值,但我觉得有一个更好的主意 - 我不知道.

提前致谢.

Sev*_*yev 11

使用设置(via NSUserDefaults)是通常的方式.为了增加好处,请设置"最后运行版本"的含义; 这样,您将有机会不仅每个应用程序生命周期运行一次代码,而且每次版本升级也运行一次.

也就是说,你的一次性代码有持久的副作用,对吧?那些钳子可能会去某个地方.因此,您可以在创建它们之前检查它们是否存在.使用一次性运行代码的结果作为再次运行它的触发器.

编辑:

NSUserDefaults *Def = [NSUserDefaults standardUserDefaults];
NSString *Ver = [Def stringForKey:@"Version"];
NSString *CurVer = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
if(Ver == nil || [Ver compare:CurVer] != 0)
{
    if(Ver == nil)
    {
        //Run once per lifetime code
    }
    //Run once-per-upgrade code, if any
    [Def setObject:CurVer forKey:@"Version"];
}
Run Code Online (Sandbox Code Playgroud)