NSMutableArray 对象在方法中不可访问
我的 .h 文件中有以下变量:
NSMutableArray *arr;
然后我有一个正在实施的方法:
void aMethod
{
if (something)
{
arr= [[NSMutableArray alloc] init];
arr = [NSMutableArray arrayWithCapacity:0];
[arr addObject:someObject];
}
现在,如果我尝试从任何其他方法甚至同一方法中的另一个 if 块访问 arr,应用程序就会崩溃,并且我无法访问该方法编曲例如:
//same method:
if (something else)
{
SomeObject *obj = [arr objectAtIndex:0]; //<---- it crashes on this line
}
有轻人吗? 提前致谢
I have the following variable in my .h file:
NSMutableArray *arr;
Then I have a method in implementation:
void aMethod
{
if (something)
{
arr= [[NSMutableArray alloc] init];
arr = [NSMutableArray arrayWithCapacity:0];
[arr addObject:someObject];
}
now if I try to access arr from any other method or even another if block within the same method, the app crashes and I can't access that arr. For example:
//same method:
if (something else)
{
SomeObject *obj = [arr objectAtIndex:0]; //<---- it crashes on this line
}
Any light guys?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这里有 2 个错误:
你有泄漏
arr= [[NSMutableArray 分配] init]; //<--here
它崩溃是因为您正在创建自动释放的对象,然后在它已经被释放时尝试访问它:
arr = [NSMutableArray arrayWithCapacity:0];
删除这一行:
There are 2 errors here:
You have a leak
arr= [[NSMutableArray alloc] init]; //<--here
it crashes cause you're creating autoreleased object and then try to access it when it is already deallocated:
arr = [NSMutableArray arrayWithCapacity:0];
remove this line:
数组的第二个 init 形成一个自动释放的实例。
这样做
The second init of the array forms an auto released instance.
Do this
您正在构造数组两次。以下两行:
第一行构造一个空数组。第二个丢弃第一行的结果,并构造另一个自动释放的空数组 - 也就是说,除非显式保留,否则不会超出当前方法。
擦除
arrayWithCapacity
行,它将按预期工作。不要忘记在dealloc
中释放。You're constructing the array twice. The following two lines:
The first one constructs an empty array. The second one throws away the results of the first line, and constructs another empty array that is autoreleased - that is, does not live beyond the current method unless explicitly retained.
Wipe the
arrayWithCapacity
line, it'll work as expected. Don't forget to release indealloc
.