在另一个函数中调用 NSMutableSet 的方法会抛出 EXC_BAD_ACCESS

发布于 2024-11-15 16:29:34 字数 525 浏览 4 评论 0原文

我被这样的代码困住了:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉宸 2024-11-22 16:29:34

您没有获得分配给 test_set 的对象的所有权,这意味着它可能会在发送 -foo2 之前被释放。一般来说,如果您需要一个对象在执行方法后继续存在,那么您应该获得它的所有权 - 例如,通过 +alloc-retain

-(void)foo1
{
  test_set=[[NSMutableSet alloc] initWithObjects:[NSNumber numberWithInt:1], nil];
  NSLog(@"count:%d",[test_set count]);
}

-(void)foo1
{
  test_set=[[NSMutableSet setWithObject:[NSNumber numberWithInt:1]] retain];
  NSLog(@"count:%d",[test_set count]);
}

: 获取和放弃对象所有权的规则在 内存管理编程指南

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:

-(void)foo1
{
  test_set=[[NSMutableSet alloc] initWithObjects:[NSNumber numberWithInt:1], nil];
  NSLog(@"count:%d",[test_set count]);
}

or

-(void)foo1
{
  test_set=[[NSMutableSet setWithObject:[NSNumber numberWithInt:1]] retain];
  NSLog(@"count:%d",[test_set count]);
}

The rules of taking and relinquishing ownership of objects are discussed in the Memory Management Programming Guide.

紙鸢 2024-11-22 16:29:34

您尚未保留 test_set。 setWithObject: 返回的集合将被自动释放。如果您

[test_set retain];

foo1() 中从 setWithObject: 获取集合后添加,并添加

[test_set release];

foo2() 的末尾,它应该可以工作。

您可能应该阅读 Cocoa 内存管理编程指南。

You haven't retained test_set. The set returned by setWithObject: will be autoreleased. If you add

[test_set retain];

after getting the set back from setWithObject: in foo1(), and add

[test_set release];

to the end of foo2(), it should work.

You should probably read the Cocoa Memory Management Programming Guide.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文