【问题标题】:In Objective-C, how does one share data among functions in a view controller?在 Objective-C 中,如何在视图控制器中的函数之间共享数据?
【发布时间】:2014-09-01 16:07:41
【问题描述】:
为了简单起见,如何在视图控制器内的函数之间共享数据?理想情况下,我想使用 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’。感谢您的输入。
【问题讨论】:
标签:
ios
objective-c
uiviewcontroller
global-variables
shared-data
【解决方案1】:
movieitem 是一个局部变量,因此不能在其他方法中使用。
因此,在方法之间共享变量的更好方法是声明一个属性。
尝试将以下代码添加到您的 XXViewController.m 文件的头部。
@interface XXViewConttroller()
@property(nonatomic,strong) NSMutableDictionary* movie;
@end
-(NSMutableDictionary*)movie{
if(!_movie){
_movie = [NSMutableDictionary dictionary];
}
return _movie;
}
我在 .m 文件中声明了一个“私有属性”,并在属性的 getter 中初始化了变量。
您可以使用 self.movie 在代码的其他部分调用该属性。
【解决方案2】:
您已经在 .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"];
...
}
【解决方案3】:
movieItem 是局部变量,只能在 viewDidLoad 方法的范围内访问。要在另一个函数中访问它,请将其设为全局或使用属性。
【解决方案4】:
您会收到该错误,因为 movieItem 是一个局部变量,仅在您创建它的 viewDidLoad 方法中有效。您需要创建一个 ivar 或属性。