删除Objective C中的对象实例(C4iOs)

时间:2013-09-14 05:15:13

标签: objective-c xcode c4

我正在尝试删除一个对象实例,但不太确定如何在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的新手,请用一种简单的语言解释一下。

1 个答案:

答案 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方法,以便从画布中添加/删除形状。该方法的工作方式如下:

  1. 首先检查形状是否超级视图
  2. 如果没有,那意味着它不在画布上,所以它添加它
  3. 如果确实有,则通过调用[shape removeFromSuperview];
  4. 将其删除

    运行示例时,您会注意到可以在画布上打开和关闭它。你可以这样做,因为形状本身就是一个对象,你已经在内存中创建并保留它。

    如果您想要完全销毁形状对象,可以将其从画布中删除,然后调用shape = nil;