Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

iphone - Objective C: store variables accessible in all views

Greetings,

I'm trying to write my first iPhone app. I have the need to be able to access data in all views. The data is stored when the user logs in and needs to be available to all views thereafter.

I'd like to create a static class, however I when I try to access the static class, my application crashes with no output on the console.

Is the only way to write data to file? Or is there another cleaner solution that I haven't thought of?

Many thanks in advance,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use a singleton class, I use them all the time for global data manager classes that need to be accessible from anywhere inside the application. You can create a simple one like this:

@interface NewsArchiveManager : NetworkDataManager
{
}

+ (NewsArchiveManager *) sharedInstance;
@end

@implementation NewsArchiveManager

- (id) init
{
    self = [super init];
    if ( self ) 
    {
         // custom initialization goes here
    }

    return self;
}


+ (NewsArchiveManager *) sharedInstance
{
    static NewsArchiveManager *g_instance = nil;

    if ( g_instance == nil )
    {
        g_instance = [[self alloc] init];
    }

    return g_instance;
}


- (void) dealloc
{
    [super dealloc];
}

@end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...