2011년 12월 6일 화요일

[C#] TCP전송 Receive 방법

public void RecevieStart()
        {
            while (true)
            {
                if (Server == null) continue;
                if (Server.Connected == false) continue;
                // 데이터 받을 변수
                byte[] receiveData = ReceiveData(Server);
             
                // 백그라운드워커는 한번에 하나씩만 실행 가능. 따라서 이벤트 핸들러를 새로 만들어 백그라운드워커 돌림
                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += new DoWorkEventHandler(bgw1_RunWorkerCompleted);
                worker.RunWorkerAsync(receiveData);
            }
        }

여기서 Server는 보내는 쪽과 연결되어 있는 소켓
Socket Server = null; 로 선언.

여기서 ReceiveData() 함수는 개인적으로 입맛에 맞게 만든 함수.
Server.ReceiveBegin( ......) 을 사용하는것과 크게 다를것이 없다.

여기서 백그라운드 워커는 받을 때 object sender 로 받는게 아니라 DoWorkEventArgs e.Argument 로 받는다.

2011년 6월 19일 일요일

[Object C] sqlite3 사용 소스

출처 : http://cafe437.daum.net/_c21_/bbs_search_read?grpid=1LrnV&fldid=Ukxs&contentval=0000Azzzzzzzzzzzzzzzzzzzzzzzzz&nenc=&fenc=&q=loop&nil_profile=cafetop&nil_menu=sch_updw


아이폰 SQLite3 샘플
iPhone 2008/11/25 14:18 
SQLite는 경량화된 DB로 맥과 아이폰/아이팟 터치에 기본적으로 내장되어 편리하게 사용할 수 있습니다. 자세한 내용은 SQLite 공식 홈페이지와 아래의 문서들을 참조하시면 도움이 되실 것입니다.


•SQLite C Interface - Functions
•SQLite In 5 Minutes Or Less
•Wikipedia - SQLite


이와함께 애플의 iPhoneDev Center에 SQLite Book List란 샘플을 보시면, 아이폰 SDK에서 사용하는 방법이 잘 나와있습니다. SQLite의 개발자인 Richard Hipp이 구글 테크토크에서 직접 SQLite에 대해서 설명하는 'An Introducion to SQLite'란 동영상도 참고하면 좋습니다.



--------------------------------------------------------------------------------



아래는 제가 SQLite를 테스트 해보기 위해 만들어 본 간단한 샘플코드입니다. 아이폰에서 사용자로 부터 입력을 받은 후에 SQLite DB에 저장하는 간단한 샘플입니다. DB를 오픈하는 부분과 SELECT, INSERT하는 부분만 참고하시면 쉽게 사용하실 수 있습니다. 


* SQLiteTestAppDelegate.h

#import! <UIKit/UIKit.h>
#import! <sqlite3.h>

@interface SQLiteTestAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    sqlite3 *db;
    NSMutableArray *dataList;

    IBOutlet UITextField *newString;
    IBOutlet UITableView *dataTable;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;

- (void)updateDataList;

- (IBAction)addRow:(id)sender;
    
@end



SQLiteTestAppDelegate.m

#import! "SQLiteTestAppDelegate.h"

@implementation SQLiteTestAppDelegate

@synthesize window;

- (void)applicationDidFinishLaunching:(UIApplication *)application {    

    // Override point for customization after application launch
    [window makeKeyAndVisible];
    
    /* 어플리케이션 패스를 구한다. */     
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mydata.db"];
        
    /* 데이터베이스를 오픈한다 */
    if(sqlite3_open([path UTF8String], &db) == SQLITE_OK) {
        char *error = NULL;
        const char* query = "SELECT count(*) from mytable";
        
        /* mytable을 쿼리해보고 오류가 있으면 mytable을 생성한다. */
        if (sqlite3_exec(db, query, NULL, 0, &error) != SQLITE_OK) {
            sqlite3_free(error);
            
            /* 테이블 생성 */
            if (sqlite3_exec(db, "CREATE TABLE mytable ('name' CHAR(16))", NULL, 0, &error) != SQLITE_OK) {
                NSLog(@"TABLE CREATE ERROR: %s", error);
                sqlite3_free(error);
            }    
        }
    } else {
        /* DB 오픈 에러 */
        sqlite3_close(db);
        db = NULL;
        
        NSLog(@"DB OPEN ERROR: '%s'", sqlite3_errmsg(db));    
    }
    
    dataList = [[NSMutableArray alloc] initWithCapacity:100];
    
    [self updateDataList];
}

- (void)applicationWillTerminate:(UIApplication *)application {
    if (db) {
        sqlite3_close(db);
    }
}

- (void)dealloc {
    [dataList release];
    
    [window release];
    [super dealloc];
}

/** 현재 DB에 있는 데이터를 dataList에 등록 */
- (void)updateDataList {
    
    /* 이전 데이터를 모두 삭제 */
    [dataList removeAllObjects];
    
    const char *query = "SELECT name FROM mytable";
    sqlite3_stmt *statement;
    
    if (sqlite3_prepare_v2(db, query, -1, &statement, NULL) == SQLITE_OK) {
        while (sqlite3_step(statement) == SQLITE_ROW) {
            
            /* dataList에 쿼리결과 등록 */
            NSString* str = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(statement, 0)];
            [dataList addObject:str];
            [str release];
        }
    }
    sqlite3_finalize(statement);

    [dataTable reloadData];
}


#pragma mark IBACTION

- (IBAction)addRow:(id)sender {

    char *error = NULL;
    
    /* 사용자가 입력한 값을 DB에 추가한다 */
    NSString *query = [NSString stringWithFormat:@"INSERT INTO mytable VALUES ('%@')", [newString text]];
    sqlite3_exec(db, [query UTF8String], NULL, 0, &error);
    
    [self updateDataList];
}


#pragma mark TextField Delegate method

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [textField resignFirstResponder];
    return YES;
}


#pragma mark TableView Delegate method

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return @"Table Items";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [dataList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
    }
    cell.text = [dataList objectAtIndex:indexPath.row];
    
    return cell;
}

@end

2011년 6월 18일 토요일

[Object C] NSZombieEnable 설정방법

http://www.cocoadev.com/index.pl?NSZombieEnabled

매우 어려워 링크.
UIAlertView가 자꾸 EXC 배드 엑세스 오류를 뱉어내며 죽는 바람에 찾아봤는데
아직까지 해결방법이 없다....

[Object C] 여러 alertView 구분 법

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if ([alertView tag] == 111) {
// 눌러진 버튼의 기본 INDEX 0입니다.
printf("User Pressed Button %d\n", buttonIndex + 1);
}
[alertView release];
}

- (void) showAlert {

UIAlertView * winAlert = [[UIAlertView alloc
                                  initWithTitle:@"알림"
                                  message:@"메시지 내용이 출력됩니다."
                                  cancelButtonTitle:nil
                                  otherButtonTitles:@"하나"@""nil];
// 태그 지정으로 알림창 닫힏때 어떤 알림창이 닫혔는지 인식함
[winAlert setTag:111];

[winAlert show];
[winAlert release];
}