开发者

NSString variable available throughout program

开发者 https://www.devze.com 2023-03-24 07:25 出处:网络
I have this line of code: NSString *dateString = [self.dates objectAtIndex:row]; that gets set when a user selects a row in a picker. I\'d like to have this code available everywhere and not just

I have this line of code:

NSString *dateString = [self.dates objectAtIndex:row];

that gets set when a user selects a row in a picker. I'd like to have this code available everywhere and not just in the picker select area. Other wise I get a "dateString" is undeclared error message of course.

how would i go about doing this?

thanks for any hel开发者_如何学Cp.


Why don't you use the singleton design pattern ? To me, it seems to be a cleaner solution that solutions posted above.

VariableStore.m

#import "VariableStore.h"

@implementation VariableStore

@synthesize dateString;

+ (VariableStore *)sharedInstance
{
    static VariableStore *myInstance = nil;

    if (nil == myInstance)
        myInstance  = [[[self class] alloc] init];

    return myInstance;
}
@end


VariableStore.h

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface VariableStore : NSObject
{
    NSString *dateString;
}

+ (VariableStore *)sharedInstance;

@property (nonatomic, retain) NSString *dateString;

@end


AnyClassWhereYouWantToUseYourVariable.h

#import "VariableStore.h"


AnyClassWhereYouWantToUseYourVariable.m

NSLog("dateString = %@", [VariableStore sharedInstance].dateString);


A simple, but not very elegant solution is to use NSUserDefaults.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
[prefs synchronize];

// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];


Define as a global variable in your interface file(.h) file. If you want to use in other class as well make the property and synthesize it.


Use this code. You can save the entire string. Just create NSString object of

in (YourDelegare.h) file

NSString * dateString;

in (YourDelegare.m) file

  -(void) saveMyState 
 {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

[prefs setObject:dateString forKey:@"dateString"];  

[prefs synchronize];
 }


- (void) retrieveMyState
{
//Retrieving

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
dateString = [prefs stringForKey:@"dateString"];


 }

just call these methods wherever required.


Or you can declare that variable in your delegate file.

In yourdelegate.h:

NSString *yourString;

@property (nonatomic, retain) NSString *yourString;

In yourdelegate.m:

@synthesize yourString;

In viewcontrolller.h:

yourdelegate *appDelegate;

In viewcontrolller.m:

appDelegate = [[UIApplication sharedApplication] delegate];  // in viewDidLoad
appDelegate.yourString = [self.dates objectAtIndex:row];  // where ever you need

And, like magic, it's a global variable now.

0

精彩评论

暂无评论...
验证码 换一张
取 消