我已经宣布了一个名为'SharedTranslationsArray'的类,我想在多个视图控制器中使用它。
然后我在视图控制器MainViewController.m中我在“ViewDidLoadMethod”中声明了一个变量的实例,并尝试在单例实例中向对象添加一个对象。没有编译错误/警告,但项目未添加到数组中。
任何建议都将不胜感激。相关代码示例如下 感谢
**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
答案 0 :(得分:2)
确保您实际初始化translation_set!
+ (SharedTranslationsArray*)sharedInstance
{
if (sharedInstance == nil) {
sharedInstance = [[super allocWithZone:NULL] init];
sharedInstance.translation_set = [NSMutableArray array];
}
return sharedInstance;
}
另外,为什么你把它称为一组但是将它声明为一个数组呢?如果对象的顺序不重要,您可以将其设为NSMutableSet