Wednesday, March 17, 2010

learning iphone programming

I start to write some code for learning iphone programming especially objective-c.

The first example shows here is an example to call ANSI C API (that is the first thing I want to figure out in the object-c environment).

/** @find_date generate date string from current time
- (char*) find_date
static char date_str[80];
struct tm * my_tm = NULL;
char *month_str[12] = {
"January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"
time_t time_val;
time_val = time(NULL);
my_tm = localtime(&time_val);
sprintf(date_str, "%s%02d", month_str[my_tm->tm_mon], my_tm->tm_mday);
return date_str;

And here is the call to find_date. (convert to NSString from C-String)

char date_str[80];
sprintf(date_str, "modified: %s", [self find_date]);
label2.text = [NSString stringWithCString: date_str];

Now another example, with given date as input, open a file and read the data from the file, returns the buffer which contains the file content.

- (char*) init_jk_quote: (char*) date_str
FILE* fp;
char* quote_buf;
int length;

fp = fopen(date_str, "r");
if (fp == NULL) return NULL;
fseek(fp, 0, SEEK_END);
length = ftell(fp);

quote_buf = (char*) malloc(length);
if (quote_buf == NULL) {
return NULL;
fseek(fp, 0, SEEK_SET);

fread(quote_buf, sizeof(char), length, fp);
return quote_buf;
- (void) free_jk_quote: (char*) quote_buf
if (quote_buf)
quote_buf = NULL;

And the call to the functions is demonstrated here.

char* quote_text;

quote_text = [self init_jk_quote: "/tmp/March17.txt"];
if (quote_text == NULL || strlen(quote_text)== 0) {
label3.text = @"not supported!";
else {
NSString* mystring = [NSString stringWithCString: quote_text];
label3.text = [@"my quote: " stringByAppendingString: mystring];
[self free_jk_quote:quote_text];

I think I need to break my habit of writing in C, and convert it to objective-c, so how to convert the above functions in object-c style? That is mainly something I need to learn.