[英]EXC_BAD_ACCESS when not using self
I got nabbed by the following bug again and would like some clarification to exactly why it is a bug. 我再次被下面的错误所困扰,并且想澄清一下为什么它是一个错误。
I have a simple UITableView that loads some data: 我有一个简单的UITableView可以加载一些数据:
// myclass.h
@property (nonatomic, retain) NSArray *myData
// myclass.m
@synthesize myData;
- (void) viewDidLoad {
...
myData = someDataSource // note the lack of self
}
- (UITableViewCell *) cellForRowAtIndexPath ... {
...
cell.textLabel.text = [self.myData objectAtIndex:indexPath.row]; // EXC_BAD_ACCESS
}
The table first loads fine, but when scrolling up enough that one of the cells is totally out of the view I then get the EXC_BAD_ACCESS error. 该表首先加载正常,但是当向上滚动到足以使其中一个单元完全不在视图范围内时,我将得到EXC_BAD_ACCESS错误。
Am I missing something in regards to @property retain. 我是否缺少有关@property保留的信息。 My understanding is that it releases anything that the pointer was previously pointing to before the reassignment.
我的理解是,它释放了指针在重新分配之前指向的所有内容。 If I am correct then why would not using self.
如果我是正确的,那为什么不使用自我。 cause any problems?
引起什么问题?
Thanks for the help. 谢谢您的帮助。
**** Update ****更新
Why is is that in all the examples that I have checked with to the release of objects within the dealloc method without the self? 为什么在我检查过的所有示例中,没有self的dealloc方法中的对象释放?
- (void) dealloc {
[someArray release];
[someTableView release];
}
If you don't use self.
如果你不使用
self.
, you are directly assigning to the instance variable myData
, which has nothing to do with the property myData
. ,您将直接分配给实例变量
myData
,它与myData
属性无关。
self.myData
is just syntactic sugar for [self myData]
or [self setMyData:newValue]
, and the synthesized property just creates the -myData
and -setMyData:
methods. self.myData
只是[self myData]
或[self setMyData:newValue]
语法糖,并且合成的属性仅创建-myData
和-setMyData:
方法。
The instance variable is just a variable, nothing more. 实例变量只是一个变量,仅此而已。 While it may have the same name, assigning to it or reading from it it is just like accessing any variable: nothing is retained, released, or in other ways modified besides the assignment.
尽管它可能具有相同的名称,但对其进行分配或读取它就像访问任何变量:除了赋值外,什么都不会保留,释放或以其他方式修改。
In case of 的情况下
myData = someDataSource;
you are giving the reference of someDataSource
(a local variable or limited scope variable) to myData
. 您正在为
myData
提供someDataSource
的引用(局部变量或有限范围变量)。 Now as soon as someDataSource
goes out of scope it gets released and as you have passed its reference to myData
it also gets released. 现在,只要
someDataSource
超出范围,它就会被释放,并且当您将其引用传递给myData
它也会被释放。
now in the case of 现在在
self.myData = someDataSource;
the value of someDataSource
is assigned to myData
. someDataSource
的值分配给myData
。 Hence whatever happens to someDataSource
myData
will retain the value. 因此,
someDataSource
myData
发生的任何情况都将保留该值。
You can also do it otherwise: 您也可以执行以下操作:
myData = [someDataSource retain];
Hope this helps. 希望这可以帮助。
Thanks, 谢谢,
Madhup Madhup
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.