ios - How to run a line of code only once for a class -


i creating class ios application deals database functions. have single class method, now, saves data. in it, create database , table. then, begin save data. happens every time method called. however, dealing single database single table, want happen once.

#import <sqlite3.h> #import "localdatabase.h"  @implementation localdatabase  + (void)savedata:(id)sender {     /* create database (if doesnt exist) */     sqlite3 *database = nil;     nsstring *path = [[nssearchpathfordirectoriesindomains(nsdocumentdirectory, nsuserdomainmask, yes) firstobject] stringbyappendingpathcomponent:@"db.sql"];     if(sqlite3_open([path utf8string], &database) != sqlite_ok) {         nslog(@"failed open database");     }      /* create table (if doesnt exist) */     char *err;     nsstring *statement = @"create table if not exists data (id integer primary key autoincrement, name text, category text)";     if (sqlite3_exec(database, statement, null, null, &err) != sqlite_ok) {         nslog(@"failed create table");     }      /* save data */     // code uses database }  @end 

i not know how static variables work in objective, think following code correct:

#import "a.h"  @implementation  static nsstring *b = @"text!!";  + (void) c {     //do stuff b }  @end 

i believe assigns @"text!!!" nsstring *b once. thought use solve problem. however, realized following not compile:

#import "a.h"  @implementation  static nsstring *b = [nsstring stringwithformat:@"%@",@"text!!!"];  + (void) c {     //do stuff b }  @end 

this means cannot make method call in assignment way. also, cannot have if-statements , such. there way can these once same way static nsstring *b = @"text!!"; once? of course can create seperate class method initialization or create static boolean keeps track of whether have initialized yet, wondering if there cleaner way.

use inside of method:

static dispatch_once_t pred; dispatch_once(&pred, ^{     // stuff once }); 

Comments

Popular posts from this blog

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

php - Magento - Deleted Base url key -

android - How to disable Button if EditText is empty ? -