Methods, Selectors, & Implementations
ในการเขียนโปรแกรม “Objective-C” นั้น “selectors” “methods” และ “implementations”เป็นคำกล่าวเรียกในมุมมองของโปรแกรมช่วงเวลา “Run-time”
In the Objective-C programming, the selectors, methods and implementations are different depended on the events as the followings:
Method: แสดงชื่อ “method” หนึ่งใน “class”
A method is a function implemented on the classes.
typedef struct objc_method *Method
Selector: Selectors ถูกใช้เพื่อแสดงถึงชื่อของ “method” ในช่วงเวลา “runtime” Selector จะถูกสร้างโดย “compiler” โดยอัตโนมัติเมื่อ “Class” ถูกโหลดเข้าไปในหน่วยความจำ
A selector is a method of an object created from a class at the run-time in the memory.
typedef struct objc_selector *SEL
Implementation: เป็นข้อมูลประเภท “Pointer” ที่บอกถึงจุดเริ่มต้นของ “Function” ที่นำไปเป็น “Method” โดยที่ “argument” แรกจะเป็น ข้อมูล “Pointer” ของตัวเอง นั้นคือหน่วยความจำสำหรับ “Instance” ของ “Class” นี้ หรือ “class method” ส่วนตัวที่สองเป็นเป็น “argument” ของ “method selector”
Implementation is the pointer of a function at the run-time. The first argument is the pointer of the instance of class (object created from run-time) and second argument is selector (or method selector).
typedef id (*IMP)(id, SEL, ...)
Selectors and Messages
โดยปกติตาม “Concept” ของ “Object-oriented” เราจะเรียกใช้ “Method” (Calling Methods) ในการเรียกเรียกใช้ “function” ต่าง ๆ ของ “Class” แต่ในการเขียนภาษา “Objective-C” มีความคิดว่าแทนที่จะเรียกใช้ ก็เปลี่ยนเป็น ส่ง “Message” แทน (Sending Message) โดยรูปแบบของ “Message” นั้นประกอบไปด้วย “argument” ภายใน […] โดยชื่อของ Message เราจะเรียกว่า “Selectors” นั้นเอง จากตัวอย่างเราใช้คำสั่ง “?debug” เพื่อให้เห็นว่าโปรแกรมจะทำการส่ง “message” ไปอย่างไร
By general, the concept of object-oriented programming, methods you can call when you want to use them. It’s different from the objective-c which use to send the messages instead. A message comprises the arguments. A name of the message is Selector. From the example, we can use ?debug command to show the application sending the message.
cy# ?debug debug == true cy# [@"hello" stringByReplacingOccurrencesOfString:@"ell" withString:@"ipp"] cy= objc_msgSend(Instance.box("hello"),"stringByReplacingOccurrencesOfString:withString:",Instance.box("ell"),Instance.box("ipp")) @"hippo"
จากตัวอย่างตั้งชื่อตัวแปร “a” และ “assign” ค่าดังข้างล่าง จากนั้นโดยสามารถเข้าถึงข้อมูล “@2” โดยส่ง “message” ตามตัวอย่าง [a …] นอกจากข้อมูลลักษณะ “Array” หรือ “Stack” แล้วรวมถึงข้อมูลประเภท “Dictionary” ด้วย
From the sample, “a” variable is assigned the value as the following. Then, we can access the data, @2 by sending the message by using command, [a…].
cy# var a = [2, 4, 6] cy= a=[2,4,6] [2,4,6] cy# [a objectAtIndex:0] cy= objc_msgSend(a,"objectAtIndex:",0) @2 cy# var o = {field: 4} cy= o={field:4} {field:4} cy# [o setObject:2 forKey:"field"]; cy= objc_msgSend(o,"setObject:forKey:",2,"field") cy# o cy= o {field:@2}