OC 中self. 与 下划线的区别

本文详细解释了iOS中@property与@synthesize指令的作用,以及self.propertyName与_propertyName的区别。阐述了属性访问与局部变量访问的不同之处,包括内存管理、懒加载支持及避免循环引用等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@property (nonatomic,copy) NSString *propertyName;

self.propertyName是对属性的访问;使用_propertyName是对局部变量的访问。

所有被声明为属性的成员,在iOS5 之前需要使用编译器指令@synthesize 来告诉编译器帮助生成属性的getter,setter方法。之后这个指令可以不用人为指定了,默认情况下编译器会帮我们生成。 编译器在生成getter,setter方法时是有优先级的,它首先查找当前的类中用户是否已定义属性的getter,setter方法,如果有,则编译器会跳过,不会再生成,使用用户定义的方法。 也就是说你在使用self.propertyName 时是在调用一个getter方法。

self.propertyName 会让计数器+1;_propertyName却不会。  

_propertyName是类似于self->_propertyName。

用self.propertyName 是更好的选择,因为这样可以兼容懒加载,同时也避免了使用下划线的时候忽视了self这个指针,后者容易在block中造成循环引用。

同时,使用_是获取不到父类的属性,因为它只是对局部变量的访问。
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) Cell In[2], line 34 32 file_path = "C:\附件\附件\C题附件.xlsx" 33 data = load_data(file_path) ---> 34 train_and_evaluate(data) Cell In[2], line 16, in train_and_evaluate(data) 14 def train_and_evaluate(data): 15 # 准备数据 ---> 16 X = data[['温度,oC', '频率,Hz', 'Bmax']] # 确保这里的列名实际数据匹配 17 y = data['损耗功率,w/m3'] # 确保这里的列名实际数据匹配 19 # 分割数据 File ~\AppData\Roaming\Python\Python312\site-packages\pandas\core\frame.py:4108, in DataFrame.__getitem__(self, key) 4106 if is_iterator(key): 4107 key = list(key) -> 4108 indexer = self.columns._get_indexer_strict(key, "columns")[1] 4110 # take() does not accept boolean indexers 4111 if getattr(indexer, "dtype", None) == bool: File ~\AppData\Roaming\Python\Python312\site-packages\pandas\core\indexes\base.py:6200, in Index._get_indexer_strict(self, key, axis_name) 6197 else: 6198 keyarr, indexer, new_indexer = self._reindex_non_unique(keyarr) -> 6200 self._raise_if_missing(keyarr, indexer, axis_name) 6202 keyarr = self.take(indexer) 6203 if isinstance(key, Index): 6204 # GH 42790 - Preserve name from an Index File ~\AppData\Roaming\Python\Python312\site-packages\pandas\core\indexes\base.py:6252, in Index._raise_if_missing(self, key, indexer, axis_name) 6249 raise KeyError(f"None of [{key}] are in the [{axis_name}]") 6251 not_found = list(ensure_index(key)[missing_mask.nonzero()[0]].unique()) -> 6252 raise KeyError(f"{not_found} not in index") KeyError: "['温度,oC', '频率,Hz'] not in index"
最新发布
03-27
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值