如何将文本字段值从一个视图传递到另一个视图xcode

时间:2012-10-13 11:02:42

标签: iphone xcode

我必须将一个UITextField值从一个视图传递到其他视图(第二个,第三个...视图)。实际上在我的第三个ViewController中我有一个scrollView,我必须在其上显示值。但是UITextField值没有得到传递它。它返回null。不可能得到什么可能是错的? 这是我正在使用的代码:

In ViewController1.m:

-(IBAction)butonclick:(id)sender{
ViewController2 *view2=[ViewController2 alloc];
view2.id=name.text; 
ViewController3 *view3=[ViewController3 alloc];
view3.id=name.text; 
[view2 release];
[view3 release];
}


IN ViewConroller2.h :
@interface ViewController2 : UIViewController { 
   NSString *id;
   UIlabel *displayId;
}

In ViewController2.m :
- (void)viewDidLoad
{
 self.displayId.text=self.id;
}

In ViewController3.h:
@interface ViewController2 : UIViewController { 
  NSString *id;
  UIlabel *dispId;
 }  

In ViewController3.m :
- (void)viewDidLoad
{
self.dispId.text=self.id;
}

但是这里的id值没有传递给ViewController3.It返回null ..我哪里出错?

3 个答案:

答案 0 :(得分:0)

AppDelegate.h中全局声明字符串,这将有助于在整个文件中保持字符串的值不变。此外,无论您想要添加字符串或更改其值还是指定它,只需导入AppDelegate.h

另请查看以下链接: -

passing NSString from one class to the other

Pass NSString from one class to another

答案 1 :(得分:0)

您正在传递值而不进行初始化。

ViewController2 *view2=[[ViewController2 alloc]init];
view2.id=name.text; 
ViewController3 *view3=[[ViewController3 alloc]init];
view3.id=name.text; 

如果您想在应用程序中全局使用对象,可以在appDelegate中声明它。

在AppDelegate.h中

 @interface AppDelegate : NSObject <NSApplicationDelegate>
    {
         NSString *idGlobal;
    }
    @property (nonatomic, retain) NSString *idGlobal;

AppDelegate.m

@synthesize idGlobal;

In ViewController1.m:

-(IBAction)butonclick:(id)sender{

     appDelegate.idGlobal=name.text; 
}

In ViewController2.m: and
In ViewController3.m:
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
id=appDelegate.idGlobal;

答案 2 :(得分:0)

我只是更正你写的代码,同时上面给出的使用AppDelegate属性的建议是一个很好的建议。 您的代码的主要问题是您只是声明NSString对象而不是使其成为属性。检查一下:

-(IBAction)butonclick:(id)sender{
ViewController2 *view2=[ViewController2 alloc]init];
view2.str=name.text; 
ViewController3 *view3=[ViewController3 alloc]init;
view3.str=name.text; 
[view2 release];
[view3 release];
}


IN ViewConroller2.h :
@interface ViewController2 : UIViewController { 
   NSString *str;
   UIlabel *displayId;
}
@property(nonatomic, retain) NSString* str; //Synthesize it in .m file

In ViewController2.m :
- (void)viewDidLoad
{
 self.displayId.text=self.str;
}

In ViewController3.h:
@interface ViewController2 : UIViewController { 
  NSString *str;
  UIlabel *dispId;
 }  
    @property(nonatomic, retain) NSString* str; //Synthesize it in .m file

In ViewController3.m :
- (void)viewDidLoad
{
self.dispId.text=self.str;
}

我不了解您的情况,但实施此类情况的最有效方法是使用代表。创建设置字符串的类的委托(ViewController1)并在其他视图控制器中相应地设置委托。

相关问题