2011-01-05 95 views
1

我有一個NSDictionary包含的價值,我需要得到這個值 我已經嘗試使用下面的代碼來獲取值:轉換的NSDictionary值NSInteger的

[NSTimer scheduledTimerWithTimeInterval:0.01 
         target:self 
           selector:@selector(timerMovelabel:) 
           userInfo: 
      [NSDictionary dictionaryWithObject:var forKey:@"var1"] 
    , [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:23] forKey:@"var2"] 

我試圖獲得的價值使用以下方法

  1. int intvar = [[[timer userInfo] objectForKey:@"var2"] intValue];

  2. NSNumber *numbervar = [[timer userInfo] objectForKey:@"var2"]; NSInteger intvar = [num intValue];

  3. 如下:

    [self method:[[[timer userInfo] objectForKey:@"var2"] intValue]]; 
    
    
    - (void)timerMovelabel:(NSTimer *)timer { 
        //here i execute one of the steps 1,2 and 3 but i didn't get any result all values are null 
    } 
    
    
    - (void) method:(NSInteger)dir 
    { 
        NSLog(@"%d",dir); 
    } 
    
+0

請使用提供的編輯器工具格式化代碼,否則會導致閱讀困難。 – 2011-01-05 16:07:42

+0

請描述這不符合您的期望以及您看到的任何警告或錯誤。它看起來像你試圖傳遞一個逗號分隔字典列表作爲你的'userInfo'參數,這沒有任何意義。向我們展示您實際使用的代碼,而不僅僅是從上下文中選擇線。 – Jonah 2011-01-05 16:21:03

+1

您錯過了'NSTimer'類方法中的'repeats'參數。 – 2011-01-05 16:27:45

回答

2

定時器的設置似乎是錯誤的。您不能將多個字典傳遞給userInfo參數。

嘗試:

[NSTimer scheduledTimerWithTimeInterval:0.01 
           target:self 
           selector:@selector(timerMovelabel:) 
           userInfo: 
     [NSDictionary dictionaryWithObjectsAndKeys: var, @"var1", 
                [NSNumber numberWithInt:23], @"var2", 
                nil] 
           repeats:NO]; 

編輯:添加重複參數,謝謝Bavarious。

+0

您錯過了'NSTimer'類方法中的'repeats'參數。 – 2011-01-05 16:28:02

+0

不錯的作品BVC。多謝。但我有1個問題什麼是使用重複參數的監禁?重複之間有什麼區別:YES和重複:NO ?? – 2011-01-06 08:09:10

+0

如果重複爲否,定時器會在第一次觸發時自動失效,否則定時器會重複給定的時間間隔。 – BVC 2011-01-07 12:23:21

1

您的userInfo構建不正確。你只需要傳遞一個對象。

[NSTimer scheduledTimerWithTimeInterval:0.01 
         target:self 
           selector:@selector(timerMovelabel:) 
           userInfo: 
    [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:23] forKey:@"var2"] 
     repeats:NO]; 

編輯:forKeys:如果您想通過與多個鍵和值的字典,那麼你就可以dictionaryWithObjects做到這一點:。

Moszi

+1

他的原始代碼指定了字典中的兩個對象,而不僅僅是一個。另外,除非'timerMovelabel:'改變字典,否則沒有理由使用'NSMutableDictionary'。 – 2011-01-05 16:26:58

+0

同意NSMutableDictionary。更新。對於dictionaryWithObjects增加了一個註釋:forKeys:。 – Moszi 2011-01-05 16:37:58