วันพฤหัสบดีที่ 21 ตุลาคม พ.ศ. 2553

การสร้างเมธอดและนำไปใช้ (ภาษา Objective-C)

Method
สำหรับไฟล์ Interface เราสามารถนิยามรูปแบบของ Method อย่างง่ายก่อน ดังนี้

<Modifier Type> "(" <Retrun Type> ")" <Method Name>
{ ":" "(" <Argument Type> ")" <Argument Name> } ";"

ตัวอย่างเช่น
-(void)print; //เครื่องหมาย - หมายถึง public สามารถรับ Message ได้อย่างสาธารณะ
-(int)numerator; //บริการขอดูค่าสมาชิกตัวแปรชื่อ numerator หรือเรียกว่าบริการ get
-(void)setNumerator:(int)n; //บริการกำหนดค่าให้กับสมาชิกตัวแปรชื่อ numerator หรือเรียกว่าบริการ set


-(int)denominator; //บริการขอดูค่าสมาชิกตัวแปรชื่อ denominator หรือเรียกว่าบริการ get
-(void)setDenominator:(int)d; //บริการกำหนดค่าให้กับสมาชิกตัวแปรชื่อ denominator หรือเรียกว่าบริการ set

และเมื่อนำมาโค้ดส่วนรายละเอียดในไฟล์ Implementation แสดงได้ดังนี้

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

-(int)numerator
{
       return numerator;
}

-(void)setNumerator:(int)n
{
       numerator = n;
}

-(int)denominator
{
       return denominator;
}

-(void)setDenominator:(int)d
{
       denominator = d;
}


***เกร็ดเล็กเกร็ดน้อย Method ข้างต้นมีบริการสำคัญคือ get และ set สำหรับขอดูและกำหนดค่าให้กับสมาชิกตัวแปรของคลาส ซึ่งเป็น Method มาตรฐานที่ควรเขียน (แล้วแต่หน้าที่ของคลาสนั้นๆ) ไว้ทุกครั้ง

ทดสอบและ Run
เปิดไฟล์ MainFraction.m แล้วเพิ่มคำสั่ง

#import "Fraction.h"

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

       [fraction setNumerator:1];
       [fraction setDenominator:2];

       [fraction print];

       [fraction release];
       return 0;
}

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

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