我正在尝试删除一个对象实例,但不太确定如何在Objective C中执行它?
我想摆脱我在屏幕上创建的椭圆
#import "C4WorkSpace.h"
#import <UIKit/UIKit.h>
C4Shape * myshape; // [term] declaration
C4Shape * secondshape;
CGRect myrect; // core graphics rectangle declaration
int x_point; // integer (whole)
int y_point;
@implementation C4WorkSpace
-(void)setup
{
// created a core graphics rectangle
myrect = CGRectMake(0, 0, 100, 100);
// [term] definition (when you allocate, make, or instantiate)
myshape = [C4Shape ellipse:myrect];
// preview of week 3
[myshape addGesture:PAN name:@"pan" action:@"move:"];
//Display the Shape
[self.canvas addShape:myshape];
}
-(void)touchesBegan {
}
@end
我是Objective-C的新手,请用一种简单的语言解释一下。
答案 0 :(得分:2)
当您使用C4(或iOS / Objective-C)时,您正在处理视图的对象。你看到的东西(如形状,图像,或任何其他类型的视觉元素)实际上坐在隐形的小窗口内。
因此,当您向画布添加某些内容时,您实际上是在画布中添加视图。画布本身也是一种观点。
当相互添加视图时,应用程序会生成“层次结构”,这样,如果向画布添加形状,画布将变为形状的 superview 和形状成为画布的 子视图。
现在,回答你的问题(我修改了你的代码):
#import "C4WorkSpace.h"
@implementation C4WorkSpace {
C4Shape * myshape; // [term] declaration
CGRect myrect; // core graphics rectangle declaration
}
-(void)setup {
myrect = CGRectMake(0, 0, 100, 100);
myshape = [C4Shape ellipse:myrect];
[myshape addGesture:PAN name:@"pan" action:@"move:"];
[self.canvas addShape:myshape];
}
-(void)touchesBegan {
//check to see if the shape is already in another view
if (myshape.superview == nil) {
//if not, add it to the canvas
[self.canvas addShape:myshape];
} else {
//otherwise remove it from the canvas
[myshape removeFromSuperview];
}
}
@end
我更改了touchesBegan方法,以便从画布中添加/删除形状。该方法的工作方式如下:
[shape removeFromSuperview];
运行示例时,您会注意到可以在画布上打开和关闭它。你可以这样做,因为形状本身就是一个对象,你已经在内存中创建并保留它。
如果您想要完全销毁形状对象,可以将其从画布中删除,然后调用shape = nil;