下面是我用来尝试使用另一种方法访问初始化字典的代码:
#import "UserFoodData.h"
@implementation UserFoodData
-(void)loadUserFoodData{
NSString *appDataPath = [[NSBundle mainBundle] pathForResource:@"UserFoodData" ofType:@"plist"];
NSMutableDictionary *userFoodDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:appDataPath];
for (userFoodDictionary in userFoodDictionary){
NSLog(@"%@", userFoodDictionary);
}
}
-(void)setName:(NSString *)foodName andCarbs:(NSNumber *)carbAmount{
[userFoodDictionary setObject:foodName forKey:foodName];
}
@end
我似乎收到的错误消息是: 使用未声明的标识符“userFoodDictionary”
现在我认为错误的是,编译器认为 setName:andCarbs 方法有可能在应用程序主屏幕初始化时调用的 loadUserFoodData 之前执行。有人可以帮我解决这个问题吗?
最佳答案
我似乎得到的错误信息是:
使用未声明的标识符“userFoodDictionary”
编译器说:
<强>1。我没有在本地看到任何变量,例如 userFoodDictionary 或 -(void)setName:(NSString *)foodName andCarbs:(NSNumber *)carbAmount 中的实例变量。
<强>2。但您正在尝试访问它。
and also your for loop has mistakes. please verify my answer
编译器正在尝试在“UserFoodData”类中查找 userFoodDictionary。因为您正在 loadUserFoodData 方法之外访问 userFoodDictionary。因此,为了访问本地方法之外的内容,您必须将该引用保存在头文件中,然后您可以在类中的任何位置访问它。
@interface UserFoodData : NSObject
@property(nonatomic,retain)NSMutableDictionary *userFoodDictionary;
@end
#import "UserFoodData.h"
@implementation UserFoodData
//@synthesize userFoodDictionary; synthesise is automatically entered by compiler
-(void)loadUserFoodData{
NSString *appDataPath = [[NSBundle mainBundle] pathForResource:@"UserFoodData" ofType:@"plist"];
self.userFoodDictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:appDataPath];
//Please not down this
for (id aFood in userFoodDictionary){
NSLog(@"%@", aFood);
}
}
-(void)setName:(NSString *)foodName andCarbs:(NSNumber *)carbAmount{
[self.userFoodDictionary setObject:foodName forKey:foodName];
}
@end
关于ios - 如何在其他方法中访问字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21324537/