วันพุธที่ 20 ตุลาคม พ.ศ. 2553

การสร้างคลาสและนำไปใช้ (ภาษา Objective-C)

ที่ผ่านมาเพื่อนๆได้พบกับ Class, Object และ Method มาแล้ว แต่อาจไม่รู้ตัว! กลับมาดูประโยคคำสั่งต่อไปนี้
NSAutoreleasePool* pool;
- เราจะเรียก NSAutoreleasePool ว่า Class
- เรียก pool ว่า Object (ซึ่งมีชนิดเป็น NSAutoreleasePool*)

pool = [[NSAutoreleasePool alloc] init];
- เราเรียก alloc และ init ว่า Method

Class
ภาษา Objective-C นิยามรูปแบบการสร้าง Class ดังนี้
- Interface (มีสกุล .h ย่อมาจาก header)
- Implementation (มีสกุล .m)

***หมายเหตุ ตัวอย่างนี้เขียนด้วยเครื่องมือชื่อ jEdit

Interface
เริ่มต้นไฟล์ใหม่ด้วย @interface ตามด้วยชื่อ Interface ท้ายสุดให้ปิดด้วย @end ดังนี้

@interface Fraction
@end

ข้างต้นนี้คือคลาส Fraction ถูกออกแบบให้สามารถดำเนินการบางสิ่งกับตัวเลข เศษ-ส่วน ครับ ฉะนั้นเพิ่มสมาชิกตัวแปร (Attribute Members) ให้กับ Fraction อีกสองค่าได้แก่ numerator สำหรับ เศษ และ denominator สำหรับ ส่วน หรือตัวหาร โดยต้องอยู่ภายใต้เครื่องหมาย { และ } เท่านั้น

@interface Fraction
{
       int numerator, denominator;
}

@end

เพิ่ม Method ชื่อ print ให้กับ Fraction สำหรับแสดงค่า เศษ-ส่วน เขียนดังนี้

@interface Fraction
{
       int numerator, denominator;
}
-(void)print;

@end

เนื่องจากคลาสที่ถูกสร้างขึ้นจะต้องมีต้นแบบ (เพื่อให้ตัวแปลภาษา (Compiler) สามารถจัดการกับหน่วยความจำได้เมื่อคลาสถูกเรียกใช้) จึงต้องสืบทอด (Inheritance) คลาสชื่อ NSObject และ #import <Foundation/Foundation.h> เข้ามาด้วย (เพราะคลาส NSObject อยู่ข้างในไฟล์ Foundation.h)

#import <Foundation/Foundation.h>


@interface Fraction : NSObject
{
       int numerator, denominator;
}
-(void)print;
@end

เสร็จแล้วให้บันทึกไว้ ณ D:\MyObjectiveC ชื่อ Fraction.h

Implementation
เริ่มต้นไฟล์ใหม่ด้วย @implementation ตามด้วยชื่อ Interface ท้ายสุดให้ปิดด้วย @end ดังนี้

#import "Fraction.h"

@implementation Fraction
@end

เขียนโค้ดส่วนแสดงผล เศษ-ส่วน ใน Method ชื่อ print

#import <Foundation/Foundation.h>

#import "Fraction.h"

@implementation Fraction
-(void)print
{
       NSLog(@"%i / %i", numerator, denominator);
}

@end

เสร็จแล้วให้บันทึกไว้ ณ D:\MyObjectiveC ชื่อ Fraction.m

ทบสอบ Run
เริ่มต้นไฟล์ใหม่ โด้ดดังนี้

#import "Fraction.h"

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

       [fraction print];

       [fraction release];

       return 0;
}

เสร็จแล้วให้บันทึกไว้ ณ D:\MyObjectiveC ชื่อ MainFraction.m ภายหลังสั่งแปลโปรแกรมด้วย

gcc -o MainFraction MainFraction.m Fraction.m
-I 'C:\GNUstep\GNUstep\System\Library\Headers'
-L 'C:\GNUstep\GNUstep\System\Library\Libraries'
-lobjc -lgnustep-base
-fconstant-string-class=NSConstantString -enable-auto-import

ไม่มีความคิดเห็น:

แสดงความคิดเห็น