Reputation: 1
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 fine 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.
Upvotes: 0
Views: 1306
Reputation: 11245
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 return NULL
, which would crash, probably with EXC_BAD_ACCESS
sending a message to a NULL
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.).
Upvotes: 0
Reputation: 5099
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 ;
}
Upvotes: 1
Reputation: 34625
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
Upvotes: 2