2012-04-01 4 views
0

こんにちは、私はアプリケーションライフで一度だけメソッドを呼び出すことができますか?私のアプリケーションはサーバーからファイルをダウンロードする必要があります。あなたがそれを行うことはできませんiOS:一度だけメソッドを呼び出す

- (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"); 

    } 
+0

あなたはinstallation_ _perちょうど1時間を意味ですか?またはアプリケーションの実行ごとに? –

+0

私はその質問に混乱しています。メソッドを一度呼び出す場合は、一度呼び出してください。 [self methodName]; –

+0

'#ifndef something //ここにコードがあります。 #endif' – 0xDE4E15B

答えて

3

フラグをNSUserDefaultsキーとして設定し、downloadCoversメソッドでこのNSUserDefault値を確認します。既に設定されている場合は何もせず、ファイルをダウンロードしてフラグをtrueに設定します。

ので、同じように:

-(void) downloadCovers { 
BOOL downloaded = [[NSUserDefaults standardUserDefaults] boolForKey: @"downloaded"]; 
if (!downloaded) { 
    //download code here 
     [[NSUserDefaults standardUserDefaults] setBool:YES forKey: @"downloaded"]; 
    } 
} 

乾杯

0
- (void)buttonsBGImage { 

     if (!mag1.backgroundImage){ 
      UIImage * bgMag1 = [self loadImage:@"mag1" ofType:@"png" inDirectory:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]]; 

       [mag1 setBackgroundImage:bgMag1 forState:UIControlStateNormal]; 
       NSLog(@"BG IS SET"); 
     } 

    } 
4

:私はインストールここ

ごとに一度だけ私の方法は

//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として画像を設定する意味意味しますメソッドを使用することができますが、pthread_onceを使用する関数で行うことができます。

static pthread_once_t once = PTHREAD_ONCE_INIT; 
pthread_once(& once, SomeFunction); 

を使用してブロックを実行するか、dispatch_once(現在の実装で最も自然な選択)を使用してブロックを1回実行することができます。

場合によっては(これ以外ではない)、+initializeで作業することもできます。

EDIT:質問は、単にファイルの存在をチェックするか、これは、複数の起動間で保持したい場合はプリファレンスを使用

を明らかにしました。

6

なぜファイルがローカルストレージに存在するかどうかをテストするだけではありません。

//Download some images from server and save it into directory 

- (void) downloadCovers { 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *pathToImg = [NSString stringWithFormat:@"%@/mag1.png",documentsDirectory]; 
    BOOL isExist = [[NSFileManager defaultManager]fileExistsAtPath:pathToImg]; 
    if (!isExist) { 
     [self saveFile:@"mag1" ofType:@"png" fromURL:@"http://myweb.com/mag1.png" inDirectory:documentsDirectory]; 
    } 

} 
+0

これはこれです。これをユーザーのデフォルトまたは他のメカニズムに基づいて設定する必要はありません。ファイルが存在する場合は、それを使用します。そうでなければ、[再]ダウンロードしてください。ある時点では、「リフレッシュ」機能が必要であることがほぼ保証されています。この機能を単純にしておくと、簡単に行えます。 – bbum

関連する問題