ios - 如何在其他方法中访问字典?

标签 ios iphone objective-c methods dictionary

下面是我用来尝试使用另一种方法访问初始化字典的代码:

#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/

相关文章:

iPhone:如何获取 UIView 的左上角坐标?

ios - 在 UITableViewCell 中为 UIView 添加渐变

objective-c - 为什么我使用 MapViewController 将无法识别的选择器发送到实例异常? (iOS)

ios - Apple Health Kit 错误 Domain=com.apple.healthkit Code=5 "Authorization not determined"

ios - #import 指令导入了错误的文件

ios - 在页脚上显示行数

ios - 当 UIPickerView 与 TextField 的 inputView 相关联时,如何重置它?

ios - 在 UIPageViewController 上将 TranslatesAutoresizingMaskIntoConstraints 设置为 No

jquery - 在 native /离线应用程序中使用 jQuery Mobile

objective-c - 从 NSMutableDictionary 中删除对象时出现 EXC_BAD_ACCESS 错误