我习惯于使用 Java 编程并使用类变量访问其他类的数据。然后我发现类变量在 Obj-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 实例不保存提交的密码,因此返回“null”。
也许这只是我的 Java 方法搞砸了,但我找不到任何其他方法所以请帮助:)!
最佳答案
Java 中的公共(public)类变量等同于 C 和 Objective-C 中的全局变量。您可以将其实现为:
class1.h
extern NSString* MyGlobalPassword;
class1.m
NSString* MyGlobalPassword = nil;
然后,任何导入 class1.h 的人都可以读取和写入 MyGlobalPassword
。
稍微好一点的方法是通过“类方法”访问它。
class1.h:
@interface Class1 : UIViewController {
UITextField *usernameField;
UITextField *passwordField;
UIButton *loginButton;
}
+ (NSString*)password;
@end
class1.m:
static NSString* myStaticPassword = nil;
@implementation Class1
+ (NSString*)password {
return myStaticPassword;
}
- (void)didClickLoginButton:(id)sender {
[myStaticPassword release];
myStaticPassword = [passwordField.text retain];
}
然后其他类将通过 password
类方法读取密码。
Class2.m :
-(void) someMethodUsingPassword {
thePassword = [Class1 password]; // This is how to call a Class Method in Objective C
NSLog(@"The password is: %@", thePassword);
}
关于Objective-c,如何从另一个类访问实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5488135/