在每次单击按钮时更改objectForKey值

时间:2014-08-14 07:33:22

标签: ios objective-c button nsdictionary plist

我在按钮点击时从plist下载一个键到我的数组,如下所示:

- (IBAction)nextKey:(id)sender {

NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
NSString *plistPath = [mainBundlePath stringByAppendingPathComponent:@"text.plist"];
NSDictionary *dict = [[NSDictionary new] initWithContentsOfFile:plistPath];
wordsArray = [dict objectForKey:@"key1"];

}

我需要在每次点击按钮时从plist更改键值。

我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

在班级中添加NSArray。和keyvalue一样。还要添加一个int变量。喜欢

NSArray *arrKey = [[NSArray alloc] initWithObjects:@"Key1",@"Key2",@"Key3",@"Key4",@"Key5", nil];
int flagKey = 0;
- (IBAction)nextKey:(id)sender {

  NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
  NSString *plistPath = [mainBundlePath stringByAppendingPathComponent:@"text.plist"];
  NSDictionary *dict = [[NSDictionary new] initWithContentsOfFile:plistPath];
  wordsArray = [dict objectForKey:[arrKey objectAtIndex:flagKey]];
  if(flagKey < arrKey.count-1){
    flagkey++;
  }

}

答案 1 :(得分:0)

您可以保持计数,每次按下按钮时,都会增加计数,如

-(IBAction)nextKey:(id)sender {
    NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
    NSString *plistPath = [mainBundlePath stringByAppendingPathComponent:@"text.plist"];
    NSDictionary *dict = [[NSDictionary new] initWithContentsOfFile:plistPath];
    wordsArray = [dict objectForKey:[NSString stringWithFormat:@"key%d",index]];
    index++;
}

或者您可以设置按钮标签,并在每次按下按钮时更改它。最初将其设置为0或在plist文件中启动键名称

-(IBAction)nextKey:(id)sender {
    UIButton *button = (UIButton *)sender;
    NSString *mainBundlePath = [[NSBundle mainBundle] bundlePath];
    NSString *plistPath = [mainBundlePath stringByAppendingPathComponent:@"text.plist"];
    NSDictionary *dict = [[NSDictionary new] initWithContentsOfFile:plistPath];
    wordsArray = [dict objectForKey:[NSString stringWithFormat:@"key%d",button.tag]];
    button.tag = button.tag + 1;
}