Objective-C中的Receiver(接收者)是什么?新手困惑求解答
Hey there, since you're new to Objective-C, let's break down the Receiver concept super simply—no jargon overload!
First, let's unpack that definition you came across:
"In Objective-C, you specify the object (known as the receiver of the method) and the message being sent to that object by enclosing the message expression in brackets."
Objective-C is a message-passing language (it's not just "calling functions" like some other languages). Think of it like a real-life conversation:
- The Receiver is the object you're talking to. It's the "who" in "who should do this thing?"
- The message is the task you're asking it to perform (the method name).
- The brackets
[]are how you wrap up this request—like tapping someone on the shoulder and giving them a job to do.
Let's use a real code example to make it click
Take this basic snippet you'll see all the time in Objective-C:
// Create a string object NSString *myString = @"I'm learning Objective-C!"; // Ask the string to tell us its length NSUInteger stringLength = [myString length];
Here:
myStringis the Receiver—it's the object we're sending a message to.lengthis the message—we're askingmyStringto calculate and return its own character length.- The brackets
[]wrap the whole request, which is Objective-C's unique way of saying "send this message to this receiver".
Another example with a custom object
Let's say we have a Dog class that can bark on command:
// Dog class definition @interface Dog : NSObject - (void)bark; // The message we can send to a Dog instance @end @implementation Dog - (void)bark { NSLog(@"Woof! Woof!"); } @end // Using the Dog class Dog *myDog = [[Dog alloc] init]; [myDog bark]; // Send the "bark" message to myDog (the Receiver)
When you run [myDog bark], myDog is the Receiver—it gets the "bark" message and executes the code to print the barking sound.
Key takeaways to remember
- A Receiver is always an object (we can also have class-level receivers for class methods, but let's stick to instance objects for now while you're learning).
- Every time you use brackets
[]in Objective-C, the item on the left is the Receiver, and the item on the right is the message you're sending it. - It's just a fancy name for "the object that's going to carry out the action you're asking for".
内容的提问来源于stack exchange,提问作者Evan Sevy

