Search code examples
memory-managementexc-bad-accessnsmutableset

Calling methods of NSMutableSet in another function throws EXC_BAD_ACCESS


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


Solution

  • 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.