为简单起见,如何在视图控制器中的功能之间共享数据?理想情况下,我想使用NSMutableDictionary,但我的方法似乎不起作用(下面):
在ViewController.m中:
- (void) viewDidLoad{
...
NSMutableDictionary * movietem = [[NSMutableDictionary alloc] init];
[movieItem setValue:@“frozen” forKey:@“title” ];
[movieItem setValue:@“PG” forKey:@“rating” ];
[movieItem setValue:@“tom cruise” forKey:@“cast” ];
....
}
-(IBAction) updateTitleBtn:(UIButton *)sender{
…
[movieItem setValue:@"lion king" forKey:@"title"];
...
}
-(IBAction) updateCastBtn:(UIButton *)sender{
…
[movieItem setValue:@"forest whitaker" forKey:@"cast"];
...
}
以错误结束:'未知接收者'movieItem'。感谢您的投入。
答案 0 :(得分:2)
您收到该错误,因为movieItem是一个局部变量,仅在您创建它的viewDidLoad方法中有效。你需要创建一个ivar或属性。
答案 1 :(得分:1)
movieitem是一个局部变量,因此不能在其他方法中使用。
因此,在方法之间共享变量的更好方法是声明属性。
尝试将以下代码添加到XXViewConttroller.m文件的头部。
@interface XXViewConttroller()
@property(nonatomic,strong) NSMutableDictionary* movie;
@end
-(NSMutableDictionary*)movie{
if(!_movie){
_movie = [NSMutableDictionary dictionary];
}
return _movie;
}
我在其中声明了一个私人财产"在.m文件中并在属性的getter中初始化变量。
您可以使用self.movie在代码的其他部分调用该属性。
答案 2 :(得分:0)
movieItem是局部变量,只能在viewDidLoad方法的范围内访问。要在其他功能中访问它,请将其设为全局或使用属性。
答案 3 :(得分:0)
您已在.m文件中的 - (void)viewDidLoad方法中创建了字典。
从这个意义上讲,您的MutableDictionary只能在viewDidLoad方法中访问。你可以将你的* movietem字典公开(可通过所有方法访问)
这是一个解决方案
在 ViewController.h 文件中 @interface ViewController:UIViewController 下面添加此代码
@property (nonatomic, strong) NSMutableDictionary *movietem;
// This line will create a public mutableDictionary which is accessible by all your methods in ViewController.m file
现在在 ViewController.m 文件中 @implementation ViewController 下添加此代码
@synthesize movietem; // This line will create getters and setters for movietem MutableDictionary
现在,您可以在任意位置使用 movietem 词典
根据您的代码,
- (void) viewDidLoad {
...
movietem = [[NSMutableDictionary alloc] init]; // allocating memory for movietem mutable Dictionary
[movieItem setValue:@“frozen” forKey:@“title” ];
[movieItem setValue:@“PG” forKey:@“rating” ];
[movieItem setValue:@“tom cruise” forKey:@“cast” ];
....
}
-(IBAction) updateTitleBtn:(UIButton *)sender {
...
[movieItem setValue:@"lion king" forKey:@"title"];
...
}
-(IBAction) updateCastBtn:(UIButton *)sender{
...
[movieItem setValue:@"forest whitaker" forKey:@"cast"];
...
}