【问题标题】:Remove Object Instances in Objective C (C4iOs)在 Objective C (C4iOs) 中删除对象实例
【发布时间】:2013-09-14 05:15:13
【问题描述】:

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

【问题讨论】:

    标签: objective-c xcode c4


    【解决方案1】:

    当您使用 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]; 将其删除

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

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

    【讨论】:

    • 非常感谢,它似乎工作得很好。解释也很棒:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多