我习惯了在Java编程访问实例变量,使用类变量来从其他类访问数据。然后我发现类变量在Obj-C中的工作方式不同,并且遇到问题。的Objective-C,如何从另一个类
我的问题是,我想在另一个类访问用户输入的密码在用户登录后,读了在不同的论坛,这样,我应该使用类的方法(+)来访问这些数据。但是因为我需要在第二类中创建第一个类的新实例,这意味着输入的密码不存在于第一类的新实例中。
我的代码如下:
class1.h
@interface class1 : UIViewController {
UITextField *usernameField;
UITextField *passwordField;
UIButton *loginButton;
NSString *password;
}
@property (nonatomic, retain) IBOutlet UITextField *usernameField;
@property (nonatomic, retain) IBOutlet UITextField *passwordField;
@property (nonatomic, retain) IBOutlet UIButton *loginButton;
@property (nonatomic, retain) NSString *password;
-(IBAction) loginButtonPushed;
+(NSString *)password;
@end
class1.m
#import "viewSwitcherViewController.h"
@implementation viewSwitcherViewController
@synthesize usernameField;
@synthesize passwordField;
@synthesize loginButton;
@synthesize password; // not needed
-(IBAction) loginButtonPushed {
password = passwordField.text; //not needed
// ...Code for switching view if successful login... EDITED:
class2 *c2 = [class2 alloc] init]; //Instantiating new class2 object
c2.password = passwordField.text; //Assigning tekst from passworField to thePassword-variable in the class2 instance.
}
class2.m
#import "class2.h"
#import "class1.h"
@implementation class2
@synthesize thePassword; //NSString variable
// this method is also not needed
-(void) someMethodUsingPassword {
class1 *c1 = [[class1 alloc] init];
thePassword = [c1 password];
NSLog(@"The password is: %@", thePassword); //This call returns null
}
所以我的问题是,在class2中创建的c1实例es不保存提交的密码,因此返回“null”。
也许这只是我的Java方法搞乱它,但我找不到任何其他方式,请帮助:)!
Tnx可能是一个很好的答案,但我没有尝试这个,因为我自己解决了这个问题。我的代码示例中遗漏的是,在Class1中,我实例化了需要密码的class2对象。所以我可以简单地通过在class1中创建的实例访问它来在class2中设置密码变量。我将编辑我的代码,以便其他人可以看到我如何解决它。 – 2011-03-31 14:47:18
对于类方法的“略微更好的方法”+1。太好了! – 2012-12-28 19:43:50