0

Aiming for simplicity, how does one share data among functions within a view controller? Ideally, I would like to use a NSMutableDictionary, but my approach doesn’t seem to work (below):

In 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"];
...
} 

Concluding in an error: ‘Unknown receiver ‘movieItem’. Thanks for the input.

4

4 回答 4

2

您会收到该错误,因为 movieItem 是一个局部变量,仅在您创建它的 viewDidLoad 方法中有效。您需要创建一个 ivar 或属性。

于 2014-07-11T05:50:54.050 回答
1

movieitem 是一个局部变量,因此不能在其他方法中使用。

因此,在方法之间共享变量的更好方法是声明一个属性。

尝试将下面的代码添加到 XXViewController.m 文件的头部。

@interface  XXViewConttroller()
@property(nonatomic,strong) NSMutableDictionary* movie;
@end

-(NSMutableDictionary*)movie{
   if(!_movie){
         _movie = [NSMutableDictionary dictionary];
   }
   return _movie;
}

我在 .m 文件中声明了一个“私有属性”,并在属性的 getter 中初始化了变量。

您可以使用 self.movi​​e 在代码的其他部分调用该属性。

于 2014-07-11T06:19:03.980 回答
0

您已经在 .m 文件中的 -(void)viewDidLoad 方法中创建了字典。
从这个意义上说,您的 MutableDictionary 只能在 viewDidLoad 方法中访问。您可以将您的 * movietem Dictionary 公开(可通过所有方法访问)
这是一个解决方案 在 @interface ViewController

下方添加此代码: UIViewController在您的ViewController.h文件中

 @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"];
...
} 
于 2014-07-11T07:58:41.760 回答
0

movieItem 是局部变量,只能在 viewDidLoad 方法的范围内访问。要在另一个函数中访问它,请将其设为全局或使用属性。

于 2014-07-11T05:54:02.450 回答