object-c 中的 self 含义

本文通过一个具体的 Objective-C 示例介绍了 self 在继承中的作用,解释了如何在子类中调用父类的方法,并展示了 self 如何帮助正确引用当前实例。

self就是当前实例的指针。

所以 看这个例子:

SuperClass

SubClass : SuperClass

#import <Foundation/Foundation.h>


@interface SuperClass : NSObject {
@private
    
}

- (void) printSelf;

@end
@implementation SuperClass

- (void) printSelf
{
    NSLog(@"%@", [[self class] description]);
}

SubClass 中的代码中的

@implementation SubClass

- (void) printSelf
{
    [super printSelf];
    
    NSLog(@"%@", [[self class] description]);
}

那么当

SubClass* subc = [[SubClass alloc] init];


[subc printSelf];

结果会输出什么呢?

2011-09-17 17:38:55.829 TestSelfClass[755:903] SubClass
2011-09-17 17:38:55.830 TestSelfClass[755:903] SubClass

是的是 SubClass 并没有 superclass.

这个特性有助于我们写copy函数,分配内存的时候分配的是子类的内存 而不是 父类的内存。





ubuntu@VM-0-6-ubuntu:~$ netstat -tuln | grep -E ":13306|:18088" tcp 0 0 0.0.0.0:18088 0.0.0.0:* LISTEN tcp 0 0 0.0.0.0:13306 0.0.0.0:* LISTEN tcp6 0 0 :::18088 :::* LISTEN tcp6 0 0 :::13306 :::* LISTEN ubuntu@VM-0-6-ubuntu:~$ telnet 127.0.0.1 13306 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. J 8.0.42��t4Gd �%Q@|k=og[4caching_sha2_password2#08S01Got timeout reading communication packetsConnection closed by foreign host. ubuntu@VM-0-6-ubuntu:~$ curl -v http://127.0.0.1:18088/ * Trying 127.0.0.1:18088... * Connected to 127.0.0.1 (127.0.0.1) port 18088 > GET / HTTP/1.1 > Host: 127.0.0.1:18088 > User-Agent: curl/8.5.0 > Accept: */* > < HTTP/1.1 302 FOUND < Server: gunicorn < Date: Fri, 28 Nov 2025 02:17:09 GMT < Connection: keep-alive < Content-Type: text/html; charset=utf-8 < Content-Length: 223 < Location: /superset/welcome/ < Permissions-Policy: browsing-topics=() < X-Frame-Options: SAMEORIGIN < X-Content-Type-Options: nosniff < Content-Security-Policy: base-uri 'self'; default-src 'self'; img-src 'self' blob: data: https://apachesuperset.gateway.scarf.sh https://static.scarf.sh/ ows.terrestris.de; worker-src 'self' blob:; connect-src 'self' https://api.mapbox.com https://events.mapbox.com; object-src 'none'; style-src 'self' 'unsafe-inline'; script-src 'self' 'strict-dynamic' 'nonce-O_dhXlWJ-g8lW7qZD6CTEwJx3JI4ddI8' < Referrer-Policy: strict-origin-when-cross-origin < Vary: Accept-Encoding < <!doctype html> <html lang=en> <title>Redirecting...</title> <h1>Redirecting...</h1> <p>You should be redirected automatically to the target URL: <a href="/superset/welcome/">/superset/welcome/</a>. If not, click the link. * Connection #0 to host 127.0.0.1 left intact ubuntu@VM-0-6-ubuntu:~$
最新发布
11-29
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值