Objective C - Singleton class instane not initialising
I have declared a class called 'SharedTranslationsArray' that I want to use in multiple view controllers.
I then in the view controller MainViewController.m I declare an instance of the variable in the "ViewDidLoadMethod" and try to add an object to the array in the singleton instance. There are no compilation errors / warning but the items are not added to the array.
Any advice would be appreciated. The relevant code samples are below Thanks
**SharedTranslations.h**
#import "Foundation/Foundation.h"
@interface SharedTranslationsArray : NSObject {
NSMutableArray *translation_set;
}
static SharedTranslationsArray *sharedInstance;
@property (nonatomic, retain) NSMutableArray *translation_set;
+ (SharedTranslationsArray*) sharedInstance;
@end
**SharedTranslations.m**
#import "SharedTranslationsArray.h"
static SharedTranslationsArray *sharedInstance;
@implementation SharedTranslationsArray
@synthesize translation_set;
\+ (SharedTranslationsArray*)sharedInstance
{
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
}
return sharedInstance;
}
\ + (id)allocWithZone:(NSZone *)zone
{
return [[self sharedInstance]retain];
}
\ - (id)copyWithZone:(NSZone *)zone
{
return self;
}
\ - (id)retain
{
return self;
}
\ - (unsigned)retainCount
{
return NSUIntegerMax; //denotes an object that cannot 开发者_运维问答be released
}
\ - (void)release
{
//do nothing
}
\ - (id)autorelease
{
return self;
}
@end
**MainViewController.m**
#import "MainViewController.h"
#import "Translations.h"
#import "SharedTranslationsArray.h"
@implementation MainViewController
\- (void)viewDidLoad {
NSMutableString *temp = [[NSMutableString alloc] init];
SharedTranslationsArray *ts = [SharedTranslationsArray sharedInstance];
Translations *translation = [Translations new];
translation.shortText = @"short";
translation.fullText = @"long";
translation.canDeleted = FALSE;
translation.active = TRUE;
[ts.translation_set addObject:translation];
}
@end
Make sure you actually initialize translation_set!
+ (SharedTranslationsArray*)sharedInstance
{
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
sharedInstance.translation_set = [NSMutableArray array];
}
return sharedInstance;
}
Also why are you calling it a set but declaring it as an array? If the order of the objects is not important you could make it an NSMutableSet
精彩评论