[英]Address is different when using pointer with __block in Objective-C
[英]Dereferencing a pointer when using NSLog in Objective-C
NSDate *now = [NSDate date];
NSLog(@"This NSDate object lives at %p", now);
NSLog(@"The date is %@", now);
好的,从这段代码中,我知道now
是一个指向NSDate
对象的指针,但是在第3行的代码中,如何在没有星号的情况下取消引用指针? 为什么我们不在第3行做这样的代码:
NSLog(@"The date is %@", *now);
%@
格式说明符采用指向对象的指针,因此无需在参数列表中取消引用指针。 通常,不需要取消引用Objective C对象的指针。
%@
获取指向对象的指针,并向其发送description
消息,该消息返回NSString
指针。 (您可以覆盖类中的description
以自定义字符串。)
添加以回应评论:
在Objective-C中,您可以使用[ objectPointer message ]
语法通过指针向对象发送消息。 因此,使用您的NSDate
示例,您可以执行以下操作:
NSDate * now = [NSDate date];
NSString * dateDescription = [now description]; // Note that "now" points to an object and this line sends it the "description" message
NSLog(dateDescription);
可以向description
消息发送从NSObject继承的类的任何实例,因此可以将指向它的指针传递给%@
format参数。
(技术说明:如果对象支持descriptionWithLocale:
消息,则会发送该消息。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.