Objective-C: Introduction to xcode

วันนี้ว่างๆนอนไม่หลับก็เลยนั่งลองเขียน Object-C ดีกว่า หลังจากที่โอ้เอ้ไม่ได้อ่านหนังสือมาตั่งนาน และเนื่องจากกลัวที่ละลืม เลยเอามาเขียนบล็อกไว้ดีกว่า

เริ่มต้นจากเปิด xcode เลือก New Project โดยเลือกเป็น Mac OS X > Application > Command Line Tool > Foundation แล้วตั่งชื่อ Project ว่า sample1

จะเห็นว่าได้ไฟล์ sample1.m ซึ่งคือไฟล์ของ Object-C โดยมีโค๊ดดังนี้


#import 

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    // insert code here...
    NSLog(@"Hello, World!");
    [pool drain];
    return 0;
}

เริ่มต้นโปรแกรมจะเห็นว่ามีส่วนของการ include lib เข้ามาซึ่งในที่นี้จะเป็น Foundation.h

#import 

จากนั้นก็เป็น main ของโปรแกรม

int main (int argc, const char * argv[]) {

ในต่อมาเป็นการ allocate memory ให้กับโปรแกรม

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

จากนั้นลองมาแสดง “Hello World” ออกจาก standard output ด้วย

    NSLog(@"Hello, World!");

และเมื่อสิ้นสุดโปรแกรม ก็ต้องคืน memory ที่ทำการ allocate ไว้ในตอนแรก แล้วก็ return 0 ซึ่งหมายถึงการ terminate program แบบปกติ ไม่มี error

    [pool drain];
    return 0;