将NSDictionary值转换为NSInteger

时间:2011-01-05 16:05:06

标签: iphone objective-c nsdictionary nsnumber

我有一个包含值的NSDictionary,我需要获得此值 我试图使用以下代码获取值:

[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);
    }
    

2 个答案:

答案 0 :(得分:2)

计时器的设置似乎是错误的。您不能将多个字典传递给userInfo参数。

尝试:

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

编辑:添加了重复参数,感谢Bavarious。

答案 1 :(得分:1)

您的userInfo未正确构建。你只需要在那里传递一个对象。

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

编辑:如果你想传递一个包含多个键和值的字典,那么你可以使用dictionaryWithObjects:forKeys:。

Moszi