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
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.
精彩评论