passing NSString from one class to the other

前端 未结 3 1382
梦毁少年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: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;
    

提交回复
热议问题