我正在尝试初始化NSMutableArray,具体取决于NSUserDefaults中是否存在,或者不使用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];
当尝试将对象添加到阵列时,我得到了#34;未知的接收者'客户。'"我不确定为什么我无法使用该阵列。
答案 0 :(得分:3)
尝试在if语句之外声明customers数组
NSMutableArray *customers;
if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] == nil) {
customers = [NSMutableArray arrayWithCapacity:10];
} else {
customers = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"]mutableCopy];
}
答案 1 :(得分:2)
我很确定你是这样写的,
NSMutableArray *customers;
if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] == nil) {
NSMutableArray *customers = [NSMutableArray arrayWithCapacity:10];
} else {
NSMutableArray *customers = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"]mutableCopy];
}
那么,这里有什么问题?
请注意,if和else创建自己的范围,因此你在if和else中声明的变量是新变量,而不是外部范围的变量。如果您想使用外部范围的客户,请按照这样做,
NSMutableArray *customers;
if ([[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] == nil) {
customers = [NSMutableArray arrayWithCapacity:10];
} else {
customers = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"customers"] mutableCopy];
}
现在,if和else块中的客户是你在if / else块之外声明的变量。