开发者

How to know who sent the message

开发者 https://www.devze.com 2023-01-28 19:34 出处:网络
It\'s the first i post to stackoverflow although i always check the forum. I am looking for a conveniant way to know who sent a message in ObjC without sending the pointer as an argument in the metho

It's the first i post to stackoverflow although i always check the forum.

I am looking for a conveniant way to know who sent a message in ObjC without sending the pointer as an argument in the method.

Can anyone help?

开发者_JAVA百科

Thanks in advance!


This is not possible in the general case (messages can be set from places where there is no self, such as the runtime or the main function), and it's impractical even where it might be technically possible, because it would require you to walk the stack and analyze the bytes there.

In practice, you shouldn't need to know the sender in most cases other than action methods. It's normally a sign of a bad design. And in any case, when you need to get a reference to another object, it should be passed as an argument to a method.

EDIT: I just stumbled on this and noticed the comment. In case anyone is wondering, the reason it's often a sign of bad design is because it creates a tight coupling between components that is almost never necessary (again, outside of action methods). Usually you can take either a delegate or a callback block to accomplish the same purpose.


No, this isn't possible without passing in a pointer to the sender of the message, like this:

- (void) someMethod:(id) sender {
}

[obj someMethod:self];


I guess you could use the hash value of the underlying NSObject (if the object is a subclass of NSObject). As an NSUInteger it's going to be the same size as the pointer, though, so not much space savings there.

Why exactly do you not want to use a pointer?

0

精彩评论

暂无评论...
验证码 换一张
取 消