Consider this function in class ABC having one instance variable as sName and i have static object of this class as obj
+ (ABC*) getInstance : (NSString *) name
{
if(obj == nil)
{
obj = [[ABC alloc] initWithName: name];
}
// checking the name is same or reinitializing it again
else if ([name isEqualToString:[obj sName]] == NO)
{
obj = [[ABC alloc] initWithName: name];
}
return obj ;
}
This snippet of code works perfectly fin开发者_C百科e on simulator, but when i run it on device. This function is getting called couple of times and third time i get "EXC_BAD_ACCESS".
What may the problem? Any suggestions to improve the code.
Static methods cannot access non static variables.
"class ABC having one instance variable as sName", and so sName
cannot be accessed in this method.
else if ([name isEqualToString:[obj sName]] == NO)
^^^^ Error
There seems to be a memory leak!!!!
Also, if sName is an instance varaible, why don't you synthesize it as a property and then call it differently:
@synthesize sName;
+ (ABC*) getInstance : (NSString *) name
{
if(obj == nil)
{
obj = [[ABC alloc] initWithName: name];
}
// checking the name is same or reinitializing it again
else if (![name isEqualToString:obj.sName])
{
//obj is not nil so if we are creating a new obj we should release the old one
[obj release]
obj = [[ABC alloc] initWithName: name];
}
return obj ;
}
Here are a few things I would look into:
the second block in the if-statement appears to leak
obj
. If called enough times, perhaps you actually run out of memory, and[ABC alloc]
will in fact start to returnNULL
, which would crash, probably withEXC_BAD_ACCESS
sending a message to aNULL
pointer.This looks suspiciously similar to a singleton initializer. It is not thread safe, so if you're calling it from multiple threads, you might want to fix that (this is not a trivial problem btw.).
精彩评论