2013년 9월 8일 일요일

sqlite3 사용 방법



+ (void)initDb {
    if (gTheDb == nil )
        [self openDatabase];
}

+ (void)openDatabase
{
    NSString *dir = [DbManager getDbPath];
    NSString *writableDBPath = [dir stringByAppendingPathComponent:kDbName];
    
    //check file
    NSFileManager *fileManager;
    fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:writableDBPath] == NO) {
        
        NSError *error;
        NSString *bundleDBPath = [[[NSBundle mainBundleresourcePathstringByAppendingPathComponent:kDbName];
BOOL success = [fileManager copyItemAtPath:bundleDBPath toPath:writableDBPath error:&error];
        if( !success )
        {
            NSLog(@"fail to create writable database into %@.(error=%@)",writableDBPath, error);
            return;
        }
    }
    
    // Open the database. 
    if (sqlite3_open([writableDBPath UTF8String], &gTheDb) != SQLITE_OK) {
        sqlite3_close(gTheDb);
        NSLog(@"Failed to open database. (%s)"sqlite3_errmsg(gTheDb));
        return;
    }
    NSLog(@"Success to open database. (%@)", writableDBPath);
}

+ (void)closeDatabase
{
    if (gTheDb) {
        sqlite3_close(gTheDb);
    }
}

+ (NSString *)getDbPath {
    NSString *path = [NSString stringWithFormat:@"%@/%@",
                      [Util getCachesPath],
                      KPATH_DB];
    // create directory
    [[NSFileManager defaultManagercreateDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    return path;
}




//일반적인 쿼리 방법
    NSString *query = @"SELECT * FROM ZMESSAGE";
    NSString *query = [NSString stringWithFormat:@"SELECT * FROM ZTHREAD WHERE Z_PK=\"%@\"",ZTHREAD];
    const char *query_stmt = [query UTF8String];
    sqlite3_stmt *statement=nil;
    if (sqlite3_prepare_v2(theOldDb, query_stmt, -1, &statement, NULL) == SQLITE_OK)
    {
        NSNumber *ZSELECTEDDEFAULTSKIN = nil;
        NSString *ZSELECTEDSKINFILENAME = @"";
        if (sqlite3_step(statement) == SQLITE_ROW) {
            ZSELECTEDDEFAULTSKIN  = [NSNumber numberWithInt: sqlite3_column_int(statement, 4)];
            if( sqlite3_column_text(statement, 9) != NULL)
            ZSELECTEDSKINFILENAME = [NSString stringWithUTF8String:(const char *) sqlite3_column_text(statement, 9)];
        }
    }
    sqlite3_finalize(statement);




// 특수 문자 입력을 위한 처리 방법
query = [NSString stringWithFormat: @"INSERT INTO tbMessage (msg_kind,mt,call_mdn,message,ret,fc,ft,subject,status,read,port_height,land_height,spam,port_emo_rects,land_emo_rects,recipient,is_multirecipient) \
         VALUES (%d,%d,\'%@\',?4,\'%@\',%d,\'%@\',?8,%d,%d,%f,%f,%d,\'%@\',\'%@\',\'%@\',%d)", \
         msgkind,type,callmdn,/*message,*/receiveTime,attachedFileCount, \
         fileType,/*subject,*/status,read,port_height,land_height,isSpam,portEmoRects,landEmoRects,recipient,is_multirecipient];
query_stmt = [query UTF8String];

if (sqlite3_prepare_v2(gTheDb, query_stmt, -1, &statement, NULL) == SQLITE_OK)
{
    sqlite3_bind_text(statement, 4, [message cStringUsingEncoding:NSUTF8StringEncoding], -1,
                      SQLITE_TRANSIENT);
    sqlite3_bind_text(statement, 8, [subject cStringUsingEncoding:NSUTF8StringEncoding], -1,
                      SQLITE_TRANSIENT);
    if (sqlite3_step(statement) != SQLITE_DONE)
        NSLog(@"[migration]Fail inserting into tbMessage");
}







브로드 캐스팅 상용 방법





#define kShowLoginActionNotification @"kShowLoginActionNotification"



- (void)viewDidLoad
{
    [super viewDidLoad];


[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLoginPage:) name:kShowLoginActionNotification object:nil];

}



- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self name:kShowLoginActionNotification object:nil];
}



- (void) showLoginPage:(NSNotification *) notification
{
  //실재 기능 구현
}



image Util 기능



//이미지 비율을 유지하면서 최대 가로사이즈보다 작은 이미지 사이즈
+ (CGSize)getScaledImageSize:(UIImage *)image scaledToMaxWidth:(CGFloat)maxWidth
{
    CGFloat oldWidth = image.size.width;
    CGFloat oldHeight = image.size.height;
    
    CGFloat scaleFactor=1;
    
    if (oldWidth > maxWidth) {
        scaleFactor = maxWidth / oldWidth;
    } else {
        //scaleFactor = height / oldHeight;
        return image.size;
    }
    
    CGFloat newHeight = oldHeight * scaleFactor;
    CGFloat newWidth = oldWidth * scaleFactor;
    CGSize newSize = CGSizeMake(newWidth, newHeight);
    return newSize;
}

//이미지 비율을 유지하면서 최대 가로 or 높이보다 작은 이미지 사이즈 생성
+ (UIImage *)getScaledImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height {
    CGFloat oldWidth = image.size.width;
    CGFloat oldHeight = image.size.height;
    
    CGFloat scaleFactor=1;
    
    if (oldWidth > width) {
        scaleFactor = width / oldWidth;
    } else if(height){
        scaleFactor = height / oldHeight;
    } else  //oldWidth<width and height==0이면, scale하지 않음.
        return image;
    
    CGFloat newHeight = oldHeight * scaleFactor;
    CGFloat newWidth = oldWidth * scaleFactor;
    
    UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight));
    [image drawInRect:CGRectMake(0, 0, newWidth, newHeight)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


//JPEG 이미지로 저장
UIImageJPEGRepresentation(scaledImage, 0.5);

//PNG 이미지로 저장
UIImagePNGRepresentation(scaledImage);




//이미지(썸네일) 캐슁 하는 방법

NSMutableDictionary *thumbnailCache_ = nil;


+ (void)initThumbnailCache {
    thumbnailCache_ = [[NSMutableDictionary alloc] initWithCapacity:20];
}


+ (UIImage *)addThumbnailToCache:(NSString *)path {
    if ([thumbnailCache_ count] >= 20) {
        id key = [[thumbnailCache_ allKeys] objectAtIndex:0];
        [thumbnailCache_ removeObjectForKey:key];
    }
    UIImage *image = [UIImage imageWithContentsOfFile:path];
    if (image) {
        [thumbnailCache_ setObject:image forKey:path];
        return image;
    }
    
    return nil;
}


+ (UIImage *)cachedThumbnail:(NSString *)fileName {
    UIImage *image = [thumbnailCache_ objectForKey:fileName];
    if (image == nil) {
        image = [Util addThumbnailToCache:fileName];
        //NSLog(@"load file image (%@)",fileName);
    } else {
        //NSLog(@"load cached image (%@)",fileName);
    }
    
    return image;
}

//실제 사용방법

NSString *imgName = @"실제 이미지 경로(이미지 이름 포함)";


img = [Util cachedThumbnail:imgName];


2013년 9월 3일 화요일

euc_kr로 변환


NSUInteger encoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingEUC_KR);
const char * eucKRString = [string cStringUsingEncoding:encoding];

Grand Central Dispatch (GCD)


// Doing something on the main thread

dispatch_queue_t myQueue = dispatch_queue_create("My Queue",NULL);
dispatch_async(myQueue, ^{
    // Perform long running process

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update the UI

    });
}); 
If you want to run a single independent queued operation and you're not concerned with other concurrent operations, you can use the global concurrent queue:

dispatch_queue_t globalConcurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

euc_kr로 바이트 수 계산

한글은 2바이트,
영어는 1바이트로 계산해서 전체 바이트 계산하는 방법




// 표시기호 '₩' 있는 경우에, length 0으로 계산되는 문제 => length계산을 위해서 다른 한글 문자로 대치함.

NSString *inputString = [myInputBoxView.text stringByReplacingOccurrencesOfString:@"₩" withString:@""];
NSData *bytes = [inputString dataUsingEncoding:0x80000422];
NSLog(@"bytes length = %d",bytes.length);


로그 :
bytes length = 16 바이트