【问题标题】:Why won't my NSMutableArray change its value when changed in an if statement in Objective - C?为什么我的 NSMutableArray 在 Objective-C 的 if 语句中更改时不会更改其值?
【发布时间】:2012-04-26 20:11:08
【问题描述】:

我试图在一个连续运行的函数中创建一个 NSMutableArray,并且只初始化一次它的值,这样它就不会在重复调用函数时继续初始化值(从而替换更改的值)。我的问题是,当我尝试在 if 语句中初始化值时,数组中的值不会改变,当我期望它打印“值为 1”时,它会继续打印“值为 0”

这是我的相关代码:

 @property (nonatomic, strong) NSMutableArray * shapeMarked;
 @synthesize shapeMarked;

 //locationManager is the function that's continuously called

 -(void) locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 
 {

 //event count is an integer that continuously increases by one each time the 
 //parent function is called, this if statement is used so that it only happens 
 //once

 if(eventcount == 1){

    for (int i = 0; i < 5; i++){

        BOOL b = YES;

        [shapeMarked addObject:[NSNumber numberWithBool:b]];

        NSLog(@"value is %d", [[shapeMarked objectAtIndex:i] boolValue] );

    }

  }
 }

【问题讨论】:

  • eventcount == 1 是否匹配过?在这种情况下添加一个 NSLog。另外,shapeMarked 实际上是一个有效的 NSArray 吗?添加NSLog(@"array: %@", shapeMarked);
  • 当我添加 NSLog(@"array ... ); 它正在输出 "array: (null).我知道“事件计数 == 1”是匹配的,因为 NSLog 输出,如果它不匹配,我不会得到输出,因为 NSLog 在 if 语句中被调用。

标签: objective-c nsmutablearray nsarray boolean


【解决方案1】:

在某处分配并初始化数组!有吗?

self.shapeMarked = [NSMutableArray array];

例如,在您的 init 方法中应该这样做。没有它,你的 shapeMarked 就是 nil。

【讨论】:

  • 有没有办法在“@property”或“@synthesize”之后的任何函数之外执行此操作,因为当我尝试在“@property”行上执行此操作时,它会给我错误。
  • 你需要去阅读基本的Objective-C指南;了解方法和类、指定的初始化程序等......那么答案将是显而易见的(并且您将拥有成功的基础)。
  • 正如我所写,试试你的 init 方法。同时释放dealloc中的对象。 Bbum 的建议肯定是个好建议。
【解决方案2】:

你的数组显然不是一个有效的NSMutableArray 实例——或者换句话说,它只是nil

那是你的代码的问题。

nil 对象上调用选择器时,返回值始终为nil(对于对象)或0(对于标量类型)。调用objectAtIndex: 将导致返回nil。您期待一个NSNumber 实例,如前所述,它将是nil。现在,您在该 nil 实例上调用 boolValue 并将返回 0,因为您期望一个标量数据类型。请参阅 Apple 优秀的Objective-C documentation

您很可能忘记使用有效的 NSMutableArray 实例初始化 shapeMarked

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2014-08-19
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多