我正在尝试使用大书呆子牧场书来教自己客观c,这是一本非常好的书,但某些方面让我很困惑.
本章讨论的是使用setValue:forKey函数,我理解这是NSObject中定义的方法.书中说你可以在像int或float这样的ac原语上使用它并给出这个例子
我有一个名为Appliance的自定义类,它是一个名为voltage的整数实例变量,用于存储当前设备的电压我初始化一个名为
appliance *a = [[appliance alloc]init];
[a setValue:[NSNumber numberWithInt:240] forKey:@"voltage"];
Run Code Online (Sandbox Code Playgroud)
然后,他设置了一个定制的电压设定器,并在其被调用时记录电压以证明其有效
-(void)setVoltage:int(x) {
NSLog(@"setting voltage to %d",x);
voltage =x;
}
Run Code Online (Sandbox Code Playgroud)
令我困惑的是NSNumber numberWithInt返回一个指向存储在堆上的NSNumber对象的指针是正确的吗?那么他如何使用%d标记记录存储在NSNumber中的整数.我明白这会记录一个整数,但不是传入的对象?此外我认为既然电压被定义为一个整数而不是指向它的指针,它就无法将地址保存到其内存中的对象上?或NSNumber强制它保持其内存地址而不实际将电压声明为指针?
对不起这一章的困惑基本上踢了我的屁股.
我需要遍历一个0的2D数组(代表开放路径)和1代表墙的数组.我必须计算从NxN网格的(0,0)到(N-1,N-1)的唯一路径的数量.我已经编写了一个递归方法来执行此操作但是我无法弄清楚为什么我的方法的遍历部分(即直线,左右移动)没有按预期工作:
public static void TraversePath(int [][] Grid, boolean[][] isTraversed, int column, int row) {
if(row < 0 || column < 0 || row > Grid[0].length || column > Grid[0].length )
return; // if you go out of bounds
if(isTraversed[column][row] == true)
return; // if you have already been to the point
if(Grid[column][row]==1) {
isTraversed[column][row] = true; // if the current point is a wall mark it as traversed
return;
}
if(Grid[column][row]!=1 && (row == Grid[0].length-1 && column == Grid[0].length-1)) { …Run Code Online (Sandbox Code Playgroud)