【发布时间】:2011-02-14 23:41:08
【问题描述】:
我有一个取自 ViewController 中的 UITextField 的 NSString。我的每个其他 ViewController 也将使用这个 NSString。如何将此 NSString 传递给其他 ViewController?
【问题讨论】:
标签: iphone objective-c cocoa-touch
我有一个取自 ViewController 中的 UITextField 的 NSString。我的每个其他 ViewController 也将使用这个 NSString。如何将此 NSString 传递给其他 ViewController?
【问题讨论】:
标签: iphone objective-c cocoa-touch
您希望在每个控制器中都有一个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
【讨论】:
banana 或 penelope
创建一个类来共享您的常用对象。使用静态方法检索它,然后对其属性进行读写。
@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;
【讨论】:
如果字符串保持不变,并且从不更改,您可以创建一个名为 define.h 的文件(没有 .m 文件)并包含以下行:
#define kMyString @"Some text"
然后在需要字符串的地方,只需导入定义文件并使用常量。
#import "defines.h"
比制作自定义类简单得多。
编辑:
没有看到您需要从文本字段中抓取。
在这种情况下,您可以将其存储为应用委托类的属性并从那里获取。可以从您应用中的任何位置访问委托。
【讨论】: