开发者

"EXC_BAD_ACCESS" when i call static function

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:

  1. 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 return NULL, which would crash, probably with EXC_BAD_ACCESS sending a message to a NULL pointer.

  2. 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.).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜