Global variable NSMuteableArray using Singleton Class(使用单例类的全局变量 NSMuteableArray)
问题描述
我在创建一种将集合传递给不同视图控制器的好方法时遇到了麻烦.例如,我创建了一个名为 Message 的自定义类,其中包含一堆属性.我想要一个全局的 NSMutableArray 存储在一个名为消息的全局变量中,我可以添加到任何地方或从任何地方获取.Stackoverflow 上的每个人都说不要使用你的 delagate 类来存储全局变量,所以我创建了一个名为 Shared 的单例类.在那里,我为 NSMutableArray 创建了一个名为 messages 的属性,如下所示:
I'm having trouble creating a nice way of passing a collection around to different view controllers. For example, I created a custom class called Message with a bunch of attributes. I want to have a global NSMutableArray of those stored in a global variable of sorts called messages that I can add to or get from anywhere. Everyone on Stackoverflow says not to use your delagate class to store global variables so I created a singleton class called Shared. In there I created a property for the NSMutableArray called messages like this:
@interface Shared : NSObject {
}
@property (nonatomic, retain) NSMutableArray *messages;
+(Shared *) sharedInstance;
@end
而我的 .h 文件是(重要的部分):
And my .h file is (the important part):
#import "Shared.h"
static Shared* sharedInstance;
@implementation Shared
@synthesize messages;
static Shared *sharedInstance = nil;
-(id) init {
self = [super init];
if (self != nil){
}
return self;
}
-(void) initializeSharedInstance {
}
+ (Shared *) sharedInstance{
@synchronized(self) {
if (sharedInstance == nil){
sharedInstance = [[self alloc] init];
[sharedInstance initializeSharedInstance];
}
return (sharedInstance);
}
}
在我的另一个视图控制器中,我首先导入Shared.h",然后试试这个:
In my other view controller, I first import "Shared.h", then try this:
[[Shared sharedInstance].messages addObject:m];
NSLog([NSString stringWithFormat:@"Shared messages = %@", [Shared sharedInstance].messages]);
它一直打印 null 而不是 m 个对象的集合.有什么想法吗?
It keeps printing null instead of the the collection of m objects. Any thoughts?
推荐答案
你需要有一个静态变量.
You need to have a static variable.
在.h中:
@interface Shared : NSObject
{
NSMutableArray *messages;
}
@property (nonatomic, retain) NSMutableArray *messages;
+ (Shared*)sharedInstance;
@end
在.m:
static Shared* sharedInstance;
@implementation Shared
@synthesize messages;
+ (Shared*)sharedInstance
{
if ( !sharedInstance)
{
sharedInstance = [[Shared alloc] init];
}
return sharedInstance;
}
- (id)init
{
self = [super init];
if ( self )
{
messages = [[NSMutableArray alloc] init];
}
return self;
}
这篇关于使用单例类的全局变量 NSMuteableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!