I come from more of an Android development background so apologies if this is a stupid question, but it’s just wracking my brain and I can’t see what is wrong. I have a Singleton Class implementation as follows:
Header file:
@interface SingletonClass : NSObject
{
}
@property(nonatomic, retain) NSMutableArray *categoryArray;
+ (SingletonClass *)sharedInstance;
- (id) init;
- (void)setCategory: (NSMutableArray *) x;
- (NSMutableArray *)getCategory;
@end
Class Implementation:
#import "SingletonClass.h"
@implementation SingletonClass
@synthesize categoryArray;
static SingletonClass *sharedInstance = nil;
+ (SingletonClass *)sharedInstance {
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
return sharedInstance;
}
- (id)init
{
self = [super init];
if (self) {
categoryArray = [[NSMutableArray alloc] init];
}
return self;
}
+ (id)allocWithZone:(NSZone*)zone {
return [self sharedInstance];
}
- (id)copyWithZone:(NSZone *)zone {
return self;
}
- (void)setCategory: (NSMutableArray *)category_array{
categoryArray = category_array;
}
- (NSMutableArray *)getCategory{
return categoryArray;
}
@end
I have 2 Tabs each of which I try to access the Singleton Object which holds the Arrays I need using:
SingletonClass* myapp = [SingletonClass sharedInstance];
categories = [myapp getCategory];
When switching tabs it works when the Singleton Object is not called, but as soon as I use it I get the SIGABRT error. (Think it’s a memory warning). Are Singleton Instances not sharable across Tabs?
Yes, singletons may certainly be shared across tabs.
a) If you’re not using ARC, then your reference counting is off.
b) This sounds like a reference counting offset (can happen with ARC, MRC or GC). There is a diagnostic mode “Enable Zombies”. Basically, it means that objects are not actually deallocated and ‘zombified’ when their reference count reaches zero. A zombified object will then note an error whenever it is messaged. You can use this and record reference counts for objects using the Zombies instrument in Instruments.