无法从另一个类访问NSString - Objective-c [英] Can't access NSString from another class — Objective-c

查看:70
本文介绍了无法从另一个类访问NSString - Objective-c的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 UITableView ,里面有一些名字。我已经从Apple提供的MasterViewController模板构建了我的应用程序。我正在尝试将所选单元格的名称存储在 NSString 中,然后在处理新 ViewController 。在那里我使用该字符串作为视图的标题。

I have a UITableView with some names in it. I have built my app from the MasterViewController template that Apple provides. I'm trying to store the name of the selected cell in a NSString and then access it in the other class that handles the new ViewController that appears when the cell is tapped. In there I use that string as the title of the view.

MasterViewController.h

@property (nonatomic, retain) NSString *theTitle;

MasterViewController.m

@synthesize theTitle;

- (void)tableView: (UITableView*)tableview didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath animated:YES];
    theTitle = cell.textLabel.text;
}

在新的ViewController.m中

In the new ViewController.m

#import "MasterViewController.m"

- (void)viewDidLoad
{
    MasterViewController* MasterViewControllerAccess = [[MasterViewController alloc] init];
    self.title = MasterViewControllerAccess.theTitle;
    NSLog("%@", [NSString stringWithFormat:@"%@", MasterViewControllerAccess.theTitle]);
}

新的ViewController链接到IB中的单元格。当我按下单元格 theTitle 返回 NULL 。但是如果我直接在 didSelectRowAtIndexPath:方法中记录它,它将返回实名。这意味着不同类之间发生了错误。出了什么问题?

The new ViewController is linked to the cell in the IB. When I press the cell theTitle returns NULL. But if I log it directly in the didSelectRowAtIndexPath:method it returns the real names. This means that something wrong occurs between the different classes. What's wrong?

推荐答案

您正在实例化 MasterViewController 的新实例,相反,您需要访问已存在的 MasterViewController 实例。请考虑遵循Apple设置详细信息项的示例(即从主设备到详细信息)。我看不出有任何理由按照你的方式设置它。在任何情况下,如果您使用导航控制器:

You are instantiating a new instance of MasterViewController, instead you need to access the MasterViewController instance that already exists. Consider following Apple's example of setting the detail item (ie from master to detail). I can't see any reason to set it the way you are doing it. In any case, if you are using a navigation controller:

#import "MasterViewController.h" // don't import .m files. Always import .h files

- (void)viewDidLoad
{
    MasterViewController* MasterViewControllerAccess = (MasterViewController*)self.navigationController.viewControllers[0]
    self.title = MasterViewControllerAccess.theTitle;
    NSLog("%@", [NSString stringWithFormat:@"%@", MasterViewControllerAccess.theTitle]);
}

这篇关于无法从另一个类访问NSString - Objective-c的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆