使用Segue传递对象
我无法理解segues以及它们如何工作和传递对象。基本上我有一个计算器,并试图绘制存储在数组中的对象。到目前为止,我有一个名为Brain的对象,它是CalculatorBrain的一个实例。现在大脑有一个NSArray属性,我用它作为堆栈来存储变量。假设我将数值3和5添加到数组中,然后想要继续。我选择了一个名为“Graph”的按钮,所以当我点击按钮后,它会继续。我将如何将大脑传递给我正在继续使用的新视图控制器?我有一个名为setGraphingPoint的属性,它在新的视图控制器中定义,我认为它应该接受传递的对象。另外,如果我通过segue传递大脑,值3和5会与它一起传递,还是会创建CalculatorBrain的新对象?这是我到目前为止。使用Segue传递对象
这是在新的视图控制器
@property (nonatomic, strong) CalculatorBrain *graphingPoint;
@synthesize graphingPoint = _graphingPoint;
-(void) setGraphingPoint:(CalculatorBrain*) graphingPoint{
_graphingPoint = graphingPoint;
[self.graphingView setNeedsDisplay];
}
这是从中将有老视图控制器称为定义按钮Segue公司
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if([segue.identifier isEqualToString:@"Graph"])
[segue.destinationViewController setGraphingPoint:[self.brain program]];
可以使用的协议。例如,你可以有你prepareForSegue是这样的:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
id destination = segue.destinationViewController;
if([destination conformsToProtocol:@protocol(GraphPointUsing)])
[destination setGraphingPoint:[self.brain program]];
}
然后你只需要确保您segueing到循规蹈矩到GraphPointUsing
的视图控制器。
如果你不想使用协议,但你还是要呼吁GraphPoint
方法,你可以这样做:
//In new ViewController suppose we want to call the method `foo` on `GraphPoint`
[self.graphingPoint foo];
//Or if we want to call a setter we can do
[self.graphingPoint setFoo:5];
我很可能会需要使用协议,感谢您的帮助,让我对它更加清楚 – 2012-07-19 23:16:12
如果有帮助,然后单击向上箭头和此答案左侧的大号复选标记:) – Nosrettap 2012-07-19 23:22:48
什么错?你能更具体地说明什么不起作用吗? – Nosrettap 2012-07-19 21:18:50
我只是不完全明白如何传递和传递对象,传递的是什么 – 2012-07-19 21:22:21
在这个例子中,你传递了一个指向对象'property'的指针。这意味着它是对原始对象的引用而不是副本。想象一下,如果我用我的手指指着一只狗。突然你走到我旁边。然后我可以告诉你也用你的手指指向狗。我们都指的是EXACT相同的对象(但请注意,狗实际上并没有移动) – Nosrettap 2012-07-19 21:27:44