【问题标题】:Accessing variables from other classes in iOS [closed]从iOS中的其他类访问变量[关闭]
【发布时间】:2024-05-16 00:45:02
【问题描述】:

我对 IOS 开发非常陌生。我知道这是一个愚蠢的问题,但我真的对此一无所知。我有两节课。让我们假设 A 和 B。在 A 类中,我有一个名为 x 的变量。我需要在我的 B 类中使用这个变量 x。我该怎么做?请用代码示例解释一下

这是我在 login.h 中的代码

#import <UIKit/UIKit.h>
#import "jsonpaser.h"
@interface LoginView : UIViewController
{
NSString* PERSON_ID;
}


@property (strong,nonatomic) IBOutlet UIScrollView *scroler;
@property (strong, nonatomic) IBOutlet UITextField *userName;
@property (strong, nonatomic) IBOutlet UITextField *passWord;
@property (strong,nonatomic) jsonpaser* jp;
@property(nonatomic,retain) NSString* PERSON_ID;


@end

在我的 login.m 类中有一个方法。在该方法中我为我的 PERSONID 变量设置了一些值

 PERSON_ID = [[responseObject valueForKey:@"d"]objectForKey:@"PersonId"];

这是我的 tableviewcontroler.h 类

#import <UIKit/UIKit.h>
#import "LoginView.h"
@interface TableViewController : UITableViewController <UITableViewDataSource>
{
LoginView* classobj;
NSString* personIDFromLogin;
}


@property (strong,nonatomic) NSArray* googlePlaces; 
@property (strong,nonatomic) NSArray* finishedArray;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *sidebarButton;
@property(retain,nonatomic) LoginView* classobj;
@property(retain,nonatomic) NSString* personIDFromLogin;
@end

这是我的 tableview.m 类

- (void)viewDidLoad
{
[super viewDidLoad];

LoginView* login = [[LoginView alloc]init];
NSString* x = login.PERSON_ID;
NSLog(@"X Variable : %@",x);

NSString* webPath = @"GetAppointmentRequests";
NSString* webURL = [NSString stringWithFormat:@"%@%@",BaseURLString,webPath];
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:x,@"caregiverPersonId", nil];

NSLog(@"PARAMETERS :%@",personIDFromLogin);


jsonpaser* parser = [[jsonpaser alloc]init];
[parser getWebServiceResponce:webURL :params success:^(NSDictionary *responseObject){



}];

}

编辑

我已经通过以下链接解决了我的问题...谢谢大家。对不起我糟糕的英语和语法错误。 refer this

【问题讨论】:

  • 了解属性
  • 你能给我一些相关的链接吗?
  • @user3256316 从 Apple 文档中了解它:Programming with Objective-C
  • 我分享了我的代码.. 但我的变量 x 为空值.. 请帮助我 :)
  • 您能否提供打开 TABLEVIEWCONTROLLER 的代码

标签: ios global-variables


【解决方案1】:

基本上,当您打开一个新的viewUITableViewController 时,您必须发送变量的值

关于TAB Button 操作

[self performSegueWithIdentifier:@"tableViewControllerSegue" sender:sender];

prepareForSegue: 方法中,只需将variable 值传递为

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"tableViewControllerSegue"])
    {   TableViewController *tableViewController = [segue destinationViewController];  
        tableViewController.personIDFromLogin = PERSON_ID;
    }
}

【讨论】:

  • 谢谢.. 你是在告诉我这就像我们在 android 中所做的那样吗?在那里,我们通过上下文传递变量。如果是这样..你能告诉我这是处理这种情况的正确方法吗?还有其他方法吗??
  • 抱歉问,实际上我在我的应用程序中使用了选项卡视图控制器。当用户按下选项卡时,就会出现这个表格视图。我没有在那里做任何编码。只使用一个segue
  • 然后尝试使用prepareForSegue:
  • 编辑了答案..请检查
  • 谢谢你的帮助..你能告诉我有没有其他方法可以做到这一点?我的意思是不传递变量,我可以像我们在android中使用全局变量一样访问吗?