How to set value for NSString in another view controller from one viewcontroller

隐身守侯 提交于 2019-12-24 19:26:32

问题


I'm using Xcode 4.3.2 & iOS 5.1 simulator, and in my project I am using two View Controllers: testingViewController, and detailView. I want to set values for an NSString in detailView once I didSelect tableViewCell in testingViewController.

For that i used following code:

testingViewController.h

testingViewController.m

detailView.h

detailView.m

I get null values for both wordName and wordMeaning in the console.

Anyone have a solution? Thanks in Advance!


回答1:


If you have a storyboard segue between testingViewController and detailView, in your testingViewController's prepareForSegue: method you should change line

detailView *dVw = [[detailView alloc] init]; 

to

detailView *dVw = (detailView *)segue.destinationViewController;

Also, I recommend you to change in your detailView.h file the

@property (nonatomic, assign) NSString *YOUR_STRING; 

to

@property (nonatomic, copy) NSString *YOUR_STRING;



回答2:


Use

[[segue destinationViewController] setWordMeaning:meaningString];
[[segue destinationViewController] setWordName:wordTapped];

The problem is that you are creating new object of the detailView




回答3:


I wrote this for sharing data between classes. I hope it is useful for you.




回答4:


Set your NSStrings to retain properties, not to assign. Also, when you change their value, always use

self.property = ...;

in order for the retain to take place. Otherwise, it will be released and you will get null or bad access.




回答5:


create custom init method

declare in .h file 

    -(id)initWithWordName:(NSString*)myWordName andWordMeaning:(NSString*)myWordMeaning;

    and in .m file

    -(id)initWithWordName:(NSString*)myWordName andWordMeaning:(NSString*)myWordMeaning
    {
       self = [super init];
       if(self)
       {
         self.wordName = myWordName;
         self.wordMeaning = myWordMeaning;
       }
       return self;
    }

and also NSString property should be copy instead of assign, do change in your detail.h file



来源:https://stackoverflow.com/questions/11651033/how-to-set-value-for-nsstring-in-another-view-controller-from-one-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!