문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top