在另一个函数中调用 NSMutableSet 的方法会抛出 EXC_BAD_ACCESS
我被这样的代码困住了:
static NSMutableSet* test_set;
-(void)foo1
{
test_set=[NSMutableSet setWithObject:[NSNumber numberWithInt:1]];
NSLog(@"count:%d",[test_set count]);
}
-(void)foo2
{
NSLog(@"pointer:%p",test_set);
NSLog(@"count:%d",[test_set count]); // here I get EXC_BAD_ACCESS
}
我只在 foo1 之后调用 foo2 。 我的调试结果是这样的:
count:1
pointer:0x262790
Program received signal: “EXC_BAD_ACCESS”.
出了什么问题? __ 有趣的说明:仅当 foo2 按计划调用时才会失败。__ 抱歉,我错过了详细信息。两者都很完美。谢谢大家
I'm stuck on such code:
static NSMutableSet* test_set;
-(void)foo1
{
test_set=[NSMutableSet setWithObject:[NSNumber numberWithInt:1]];
NSLog(@"count:%d",[test_set count]);
}
-(void)foo2
{
NSLog(@"pointer:%p",test_set);
NSLog(@"count:%d",[test_set count]); // here I get EXC_BAD_ACCESS
}
I calling foo2 only after foo1.
My debug out is like:
count:1
pointer:0x262790
Program received signal: “EXC_BAD_ACCESS”.
What's wrong?
__
Intresting note: it fails only when foo2 is calling in schedule.__ Sorry, I missed details. Both works perfect. Thank you all
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您没有获得分配给
test_set
的对象的所有权,这意味着它可能会在发送-foo2
之前被释放。一般来说,如果您需要一个对象在执行方法后继续存在,那么您应该获得它的所有权 - 例如,通过+alloc
或-retain
或
: 获取和放弃对象所有权的规则在 内存管理编程指南。
You’re not taking ownership of the object being assigned to
test_set
, which means that it might be deallocated before-foo2
is sent. In general, if you need an object to survive after the execution of a method then you should take ownership of it — for example, via+alloc
or-retain
:or
The rules of taking and relinquishing ownership of objects are discussed in the Memory Management Programming Guide.
您尚未保留 test_set。
setWithObject:
返回的集合将被自动释放。如果您在
foo1()
中从setWithObject:
获取集合后添加,并添加到
foo2()
的末尾,它应该可以工作。您可能应该阅读 Cocoa 内存管理编程指南。
You haven't retained test_set. The set returned by
setWithObject:
will be autoreleased. If you addafter getting the set back from
setWithObject:
infoo1()
, and addto the end of
foo2()
, it should work.You should probably read the Cocoa Memory Management Programming Guide.