【问题标题】:Dictionary Scope?字典范围?
【发布时间】:2012-07-07 12:36:43
【问题描述】:

我这样声明我的字典:

@property (weak, nonatomic) NSMutableDictionary *testVariableValues;
@synthesize testVariableValues = _testVariableValues;

然后,我像这样填充字典:

- (IBAction)testPressed:(UIButton *)sender {

    self.testVariableValues = [NSMutableDictionary dictionary];

    if ([sender.currentTitle isEqualToString:@"Test 1"])
    {
        [self.testVariableValues setObject:[NSNumber numberWithDouble:5.2] forKey:@"x"];
        [self.testVariableValues setObject:[NSNumber numberWithInt:-1] forKey:@"y"];
        [self.testVariableValues setObject:[NSNumber numberWithInt:1] forKey:@"a"];
    } else if ([sender.currentTitle isEqualToString:@"Test 2"]) {
    // Continues like this

每次我填充字典时,我都会将字典的内容打印到命令行,这样我就知道该部分正在工作,如果我尝试从另一种方法访问字典,问题似乎就会出现,比如这个:

if ([self.display.text isEqualToString:@"x"]) {
    NSLog(@"%f", [[self.testVariableValues objectForKey:@"x"] doubleValue]);
    [self.brain pushOperand:[[self.testVariableValues objectForKey:@"x"] doubleValue]];

这段代码中的NSLog返回null,这让我觉得我无法从testPressed方法之外访问字典。有人能对此有所了解吗?我对字典的实现全错了吗?

谢谢!

【问题讨论】:

    标签: objective-c ios xcode dictionary scope


    【解决方案1】:

    你的字典应该是一个强属性,因为如果你让它变弱,字典将在testPressed方法结束执行时被释放

    你应该改变

    @property (weak, nonatomic) ...
    

    @property (strong, nonatomic) ...
    

    【讨论】:

      【解决方案2】:

      声明具有强属性的字典属性:

      @property (strong, nonatomic) NSMutableDictionary *testVariableValues;
      

      【讨论】:

        猜你喜欢
        • 2014-11-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-21
        • 2017-05-20
        • 1970-01-01
        相关资源
        最近更新 更多