简体   繁体   English

NSMutableArray初始化后未知

[英]NSMutableArray unknown after initialization

I am trying to initialize an NSMutableArray depending on if one exists in NSUserDefaults or not using and if/else statement. 我正在尝试根据是否在NSUserDefaults中存在一个NSMutableArray进行初始化,或者不使用if / else语句。

if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] == nil) {
    NSMutableArray *customers = [NSMutableArray arrayWithCapacity:10];
} else {
    NSMutableArray *customers = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"]mutableCopy];
}

Customer *c = [[Customer alloc]init];

c.fName = self.fnameTextField.text;
c.lName = self.lnameTextField.text;
c.username = self.usernameTextField.text;
c.balance = [self.depositTextField.text floatValue];

[customers addObject:c];

[[NSUserDefaults standardUserDefaults] setObject:customers forKey:@"customers"];
[[NSUserDefaults standardUserDefaults] synchronize];

When trying to add an object to the array, I get "Unknown receiver 'customers.'" I'm not sure why I'm not able to use the array. 尝试将对象添加到数组时,出现“未知的接收方“客户”。”我不确定为什么无法使用数组。

Try declaring the customers array outside your if statement 尝试在if语句之外声明客户数组

NSMutableArray *customers;
if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] == nil) {
   customers = [NSMutableArray arrayWithCapacity:10];
} else {
   customers = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"]mutableCopy];
}

I am quite sure you have written it like this, 我很确定你是这样写的,

NSMutableArray *customers;

if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] == nil) {
    NSMutableArray *customers = [NSMutableArray arrayWithCapacity:10];
} else {
    NSMutableArray *customers = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"]mutableCopy];
}

So, what is wrong here? 那么,这是怎么了?

Note that if and else create their own scope, so the variable you declare inside if and else are new variable, not the one from outer scope. 请注意,if和else创建自己的范围,因此在if和else内部声明的变量是新变量,而不是外部范围的变量。 If you want to use customers from outer scope, do it like this, 如果您想从外部使用客户,请按以下步骤操作:

NSMutableArray *customers;

if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] == nil) {
   customers = [NSMutableArray arrayWithCapacity:10];
} else {
   customers = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] mutableCopy];
}

Now, customers inside if and else block is the same variable that you have declared outside the if/else block. 现在,if和else块内的客户与您在if / else块外声明的变量相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM