【发布时间】:2014-10-06 23:26:27
【问题描述】:
我正在尝试使用 Objective-C 制作 iOS 应用程序。但是,我遇到了一个问题。基本上,我在一个类中设置 myVariable 的值,然后尝试在另一个类中使用它。这是我的代码。
//This is in Class2
#import Class1
Class1 *class = [[Class1 alloc] init];
//Then I try to log my variable
NSLog(@"%@", Class1.myVariable);
我不想将 myVariable 设置为 class2 中的任何值,因为我希望它保持与 class1 中相同的值。但是,使用我的代码,myVariable 在 class2 中返回 (null)。在 class1 myVariable 是 6。有人认为他们可以帮助我吗?谢谢!
这是我在 Class1 中的代码示例。
- (IBAction)six:(id)sender {
_numberOfDice = 6;
[self saveNumber];
self.checkmark.hidden = YES;
self.checkmark2.hidden = YES;
self.checkmark3.hidden = YES;
self.checkmark4.hidden = YES;
self.checkmark5.hidden = YES;
self.checkmark6.hidden = NO;
}
-(void) saveNumber {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths lastObject];
NSString *filePath = [documentPath stringByAppendingPathComponent:@"number"];
_amountString = [NSString stringWithFormat:@"%d", _numberOfDice];
BOOL isSuccessful = [NSKeyedArchiver archiveRootObject:_amountString toFile:filePath];
if(isSuccessful) {
NSLog(@"It has saved.");
NSLog(@"the string is %@", _amountString);
NSLog(@"The integer is %d", _numberOfDice);
}
}
-(void) loadNumber {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [paths lastObject];
NSString *filePath = [documentPath stringByAppendingPathComponent:@"number"];
_amountString = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
if(!_amountString) {
_amountString = [[NSString alloc] init];
}
}
正如你在上面的代码中看到的,有人可以点击按钮 6,并且 _numberOfDice 设置为 6。然后我将其转换为字符串并保存该字符串。当我运行 viewDidLoad 时,我会加载数字。 string(_amountString) 是我要传递给 Class2 的变量。我把它设置在 Class1 中,然后我想将它传递给 Class2。
【问题讨论】:
-
发布
Class1的代码。很可能发生的事情是您在Class1中有代码在一段时间后设置 myVariable = 6。但是,当您执行Class1 *class = [[Class1 alloc] init];时,您会创建一个全新的Class1副本。这意味着如果您没有在init或viewDidLoad中设置myVariable,那么它还不会被设置。 -
是的,我确实在 Class1 中设置了 myVariable = 6。基本上它是一个设置视图控制器。您可以单击您希望 myVariable 等于多少。如果您单击 6,它将等于 6。然后我保存金额,现在我尝试将 6(或该人单击的任何数字)传递给 Class2。
-
您正在 Class2 中创建 Class1 的新对象。这是一个质量很低的问题。
-
@user3754646 查看我对为什么它不起作用的回答。请查看类实例的含义,以了解您的代码为何无法按预期工作。如果这是您第一次使用任何语言进行编程,那么我建议您选择一本编程入门书。
标签: ios objective-c variables