passing NSString from one class to the other

前端 未结 3 1375
梦毁少年i
梦毁少年i 2020-12-22 02:50

I have a NSString that is taken from a UITextField in a ViewController. Every of my other ViewController will use this NSString as well. How can I pass this NSString to othe

相关标签:
3条回答
  • 2020-12-22 03:31

    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 讨论(0)
  • 2020-12-22 03:36

    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;
    
    0 讨论(0)
  • 2020-12-22 03:52

    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

    0 讨论(0)
提交回复
热议问题