开发者

passing NSString from one class to the other

开发者 https://www.devze.com 2023-02-10 17:14 出处:网络
I have a NSString that is taken from a UITextFi开发者_如何转开发eld in a ViewController. Every of my other ViewController will use this NSString as well. How can I pass this NSString to others ViewCon

I have a NSString that is taken from a UITextFi开发者_如何转开发eld in a ViewController. Every of my other ViewController will use this NSString as well. How can I pass this NSString to others ViewControllers?


You want to have a property in each of your controllers

@interface MyViewController : UIViewController{
    NSString *title;
}
@property (retain) NSString *title;
@end;


@implementation MyViewController
@synthesize title;
@end;

Use it like:

MyViewController *myVC = [[MyViewController alloc] initWithFrame:...];
myVC.title = @"hello world";

You should be familiar with Memory Management


Create a class for sharing your common objects. Retrieve it using a static method, then read and write to its properties.

@interface Store : NSObject {
    NSString* myString;
}

@property (nonatomic, retain) NSString* myString;

+ (Store *) sharedStore;

@end

and

@implementation Store

@synthesize myString;    

static Store *sharedStore = nil;

// Store* myStore = [Store sharedStore];
+ (Store *) sharedStore {
    @synchronized(self){
        if (sharedStore == nil){
            sharedStore = [[self alloc] init];
        }
    }

    return sharedStore;
}

// your init method if you need one

@end

in other words, write:

Store* myStore = [Store sharedStore];
myStore.myString = @"myValue";

and read (in another view controller):

Store* myStore = [Store sharedStore];
myTextField.text = myStore.myString;


If the string remains the same, and never changes, you could make a file named defines.h (without the .m file) and have this line:

#define kMyString   @"Some text"

Then wherever you need the string, just import the defines file and use the constant.

#import "defines.h"

Much simpler than making custom classes.

EDIT:

Didn't see you needed to grab from the text field.

In that case, you could have it stored as property of your app delegate class and get it from there. The delegate can be accessed from anywhere in your app.

0

精彩评论

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