无法从另一个类访问NSString – Objective-c
我有一个UITableView
有一些名字。 我从Apple提供的MasterViewController模板构build了我的应用程序。 我试图将所选单元格的名称存储在一个NSString
,然后在处理单元格被点击时出现的新ViewController
的其他类中进行访问。 在那里,我使用该string作为视图的标题。
在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中
#import "MasterViewController.m" - (void)viewDidLoad { MasterViewController* MasterViewControllerAccess = [[MasterViewController alloc] init]; self.title = MasterViewControllerAccess.theTitle; NSLog("%@", [NSString stringWithFormat:@"%@", MasterViewControllerAccess.theTitle]); }
新的ViewController链接到IB中的单元格。 当我按下单元格时, theTitle
返回NULL
。 但是,如果我直接在didSelectRowAtIndexPath:
方法中logging,它将返回实名。 这意味着不同类别之间会发生错误。 怎么了?
您正在实例化一个MasterViewController
的新实例,而您需要访问已存在的MasterViewController
实例。 考虑以下苹果的例子设置细节项目(即从主到细节)。 我看不出有什么理由像你这样做。 无论如何,如果您使用的是导航控制器:
#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]); }
在推送视图控制器的viewDidLoad
中,您分配一个MasterViewController
的新实例,它与现有的主视图控制器(已从故事板或nib文件中加载)完全不同并且无关。 因此MasterViewControllerAccess.theTitle
是nil
。
正如在上面的评论中所说的那样,通过反向传递信息(从主视图到详细视图控制器)通常更容易,例如在prepareForSegue
就像在模板应用程序中一样。
- 初始化从另一个ViewController接收数据
- didRegisterForRemoteNotificationsWithDeviceToken不会在ios 9中调用
- 如何使用iOS中的CLLocationManager获取当前位置
- ARKit和Vuforia – 标记识别
- AVCaptureSession旋转| 定位同时传输video
- 如何使用应用程序委托中的视图控制器的function?
- UIView上的UITapGestureRecognizer和它的子视图在子视图被抽头时一起响应
- 在NSObject类中使用AVAudioPlayer播放audio
- Block_release在后台线程上取消分配UI对象