使用Singleton类的全局变量NSMuteableArray [英] Global variable NSMuteableArray using Singleton Class

查看:191
本文介绍了使用Singleton类的全局变量NSMuteableArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法创建将集合传递给不同视图控制器的好方法。例如,我创建了一个名为Message的自定义类,其中包含许多属性。我希望有一个全局的NSMutableArray存储在一个名为消息的全局变量中,我可以添加到任何地方或从中获取。 Stackoverflow上的每个人都说不要使用你的delagate类存储全局变量,所以我创建了一个名为Shared的单例类。在那里,我为NSMutableArray创建了一个名为message的属性:

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?

推荐答案

你需要一个静态变量。

在.h:

@interface Shared : NSObject
{
    NSMutableArray *messages;
}

@property (nonatomic, retain) NSMutableArray *messages;

+ (Shared*)sharedInstance;

@end

in .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;
}

这篇关于使用Singleton类的全局变量NSMuteableArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆