【发布时间】:2012-02-25 00:44:51
【问题描述】:
由于某种原因,属性的自定义设置器永远不会被调用。所以它在运行时总是以 nil 的形式出现。
我有一个视图控制器,它创建一个 NSValue 对象的 NSArray 并将其作为属性传递给视图。但是,该属性始终为 nil,即使我使用调试器验证视图控制器中的 NSArray 是否正常。
视图控制器 @interface GraphingViewController() @property (nonatomic, weak) IBOutlet GraphingView *graphingView; @结束
- (void) determinePointsOnGraph
{
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
NSMutableArray *pointsForGraph = [[NSMutableArray alloc] init];
float startingPoint = -250;
for (int i = 0; i < 500; i++) {
float x = startingPoint;
startingPoint++;
[dict setValue:[NSNumber numberWithFloat:x] forKey:[NSString stringWithString:@"x"]];
float y = [CalculatorBrain runProgram:[self graph] usingVariableValues:dict];
[pointsForGraph addObject:[NSValue valueWithCGPoint:CGPointMake(x,y)]];
}
//This calls the pointer to the view, and the setter for the view's property
[self.graphingView setPointsOnGraph:pointsForGraph];
}
查看
@synthesize pointsOnGraph = _pointsOnGraph;
- (void)setPointsOnGraph:(NSArray *)pointsOnGraph
{
//Custom setter for property, never gets called if a break point is put here
_pointsOnGraph = pointsOnGraph;
[self setNeedsDisplay];
}
- (void)drawLine:(NSArray *)pointsOfLine inContext:(CGContextRef)context
{
CGPoint pointsOfLineAsCGPoints[[pointsOfLine count]];
for (int i = 0; i < sizeof(pointsOfLineAsCGPoints); i++) {
pointsOfLineAsCGPoints[i] = [[pointsOfLine objectAtIndex:i] CGPointValue];
}
CGContextAddLines(context, pointsOfLineAsCGPoints, sizeof(pointsOfLine));
CGContextClosePath(context);
CGContextStrokePath(context);
}
drawLine 方法由drawRect 调用,并作为pointsOfLine 传递给pointsOnGraph 属性。即使我在 drawRect 中放置一个断点并查看 pointsOnGraph 属性,它在视图中始终为零。然而,当它被视图控制器传递给视图时,它包含数百个对象。
我只是不明白为什么该属性总是 nil,如果我在 setter 中设置一个断点,它就永远不会被调用。
更新 我已经验证第一次调用视图时对视图的 faceView 引用为零,但 IBOutlet 似乎已正确连接,并且视图最终会显示。似乎在 self.graphingView IBOutlet 初始化之前调用了视图控制器方法
以下内容来自我从视图控制器
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:@"Graphing"] ) {
[segue.destinationViewController setGraph:[[self.brain program] mutableCopy]];
[segue.destinationViewController determinePointsOnGraph];
}
}
解决方案 在 viewDidLoad 委托中调用 determinePointsOnGraph 方法,而不是在准备 segue 中。这可确保已创建视图。我还遇到了另一个问题,即从视图中访问视图控制器中数据的出口没有在视图设置器中初始化。
【问题讨论】:
标签: iphone objective-c ios nsarray setter