【问题标题】:passing NSString from one class to the other将 NSString 从一个类传递到另一个类
【发布时间】:2011-02-14 23:41:08
【问题描述】:

我有一个取自 ViewController 中的 UITextField 的 NSString。我的每个其他 ViewController 也将使用这个 NSString。如何将此 NSString 传递给其他 ViewController?

【问题讨论】:

    标签: iphone objective-c cocoa-touch


    【解决方案1】:

    您希望在每个控制器中都有一个property

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

    像这样使用它:

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

    你应该熟悉Memory Management

    【讨论】:

    • 你是说每个 MyViewController 都应该有一个 NSString * 标题?
    • 这只是一个例子。您也可以将该成员命名为 bananapenelope
    • MyViewController2 想用这个标题怎么办?
    • 在不同类的对象中有标题是绝对可以的。好像你还没有理解面向对象的编程。检查这个:developer.apple.com/library/ios/#documentation/cocoa/conceptual/…
    【解决方案2】:

    创建一个类来共享您的常用对象。使用静态方法检索它,然后对其属性进行读写。

    @interface Store : NSObject {
        NSString* myString;
    }
    
    @property (nonatomic, retain) NSString* myString;
    
    + (Store *) sharedStore;
    
    @end
    

    @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
    

    换句话说,写:

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

    并阅读(在另一个视图控制器中):

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

    【讨论】:

    • 如果您在 viewcontroller1 中写入 myStore 并且您想在 viewcontroller2 中读取在 viewcontroller1 中写入的相同值怎么办?我猜上面的解决方案行不通
    • EquinoX:以上方法都可以。阅读单身课程。这种方法比在每个视图控制器中使用相同的“标题”字段要干净得多。
    【解决方案3】:

    如果字符串保持不变,并且从不更改,您可以创建一个名为 define.h 的文件(没有 .m 文件)并包含以下行:

    #define kMyString   @"Some text"
    

    然后在需要字符串的地方,只需导入定义文件并使用常量。

    #import "defines.h"
    

    比制作自定义类简单得多。

    编辑:

    没有看到您需要从文本字段中抓取。

    在这种情况下,您可以将其存储为应用委托类的属性并从那里获取。可以从您应用中的任何位置访问委托。

    【讨论】:

    • 只有当用户第一次从 UITextField 输入时,字符串才会改变
    猜你喜欢
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 2013-02-08
    相关资源
    最近更新 更多