嗨,我想知道如何才能在应用程序生命中只调用一次方法。我的应用程序应该从服务器下载一些文件,而我只需要执行一次。我的意思是每次安装仅一次
这是我的方法
//Download some images from server and save it into directory
- (void) downloadCovers {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self saveFile:@"mag1" ofType:@"png" fromURL:@"http://myweb.com/mag1.png" inDirectory:documentsDirectory];
}
并且此方法将图像设置为UIButton BG:
- (void)buttonsBGImage {
UIImage * bgMag1 = [self loadImage:@"mag1" ofType:@"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
[mag1 setBackgroundImage:bgMag1 forState:UIControlStateNormal];
NSLog(@"BG IS SET");
}
最佳答案
将标志设置为NSUserDefaults键,并在downloadCovers方法中检查此NSUserDefault值。如果已经设置,则什么也不做,否则下载文件并将标志设置为true。
像这样:
-(void) downloadCovers {
BOOL downloaded = [[NSUserDefaults standardUserDefaults] boolForKey: @"downloaded"];
if (!downloaded) {
//download code here
[[NSUserDefaults standardUserDefaults] setBool:YES forKey: @"downloaded"];
}
}
干杯