1

我被困在这样的代码上:

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 按计划调用时它才会失败。__ 对不起,我错过了细节。两者都完美无缺。谢谢你们

4

2 回答 2

0

您没有获得分配给 的对象的所有权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]);
}

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

于 2011-06-15T13:05:51.640 回答
0

您还没有保留 test_set。返回的集合setWithObject:将被自动释放。如果你添加

[test_set retain];

setWithObject:从in取回集合后foo1(),并添加

[test_set release];

到最后foo2(),它应该可以工作。

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

于 2011-06-15T13:06:22.837 回答