Remove Object Instances in Objective C (C4iOs)

791 views Asked by At

I am trying to remove an object instance, but not quite sure how to do it in Objective C?

I would like to get rid of that ellipse I created put on the screen

#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 

I am really new to Objective-C, Please explain it in a bit easy language.

1

There are 1 answers

1
C4 - Travis On BEST ANSWER

When you're working with C4 (or iOS / Objective-C) you're working with objects that are views. The things you see (like shapes, or images, or any other kind of visual element) actually sitting inside invisible little windows.

So, when you add something to the canvas, you're actually adding a view to the canvas. The canvas itself is also a view.

When adding views to one another the app makes a "hierarchy" so that if you add a shape to the canvas, the canvas becomes the shape's superview and the shape becomes a subview of the canvas.

Now, to answer your question (I modified your code):

#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

I changed the touchesBegan method to add / remove the shape from the canvas. The method works like this:

  1. It first checks to see if the shape has a superview
  2. If it doesn't, that means its not on the canvas so it adds it
  3. If it does have one, it removes it by calling [shape removeFromSuperview];

When you run the example you'll notice that you can toggle it on and off the canvas. You can do this because the shape itself is an object and you've created it in memory and kept it around.

If you ever want to completely destroy the shape object, you could remove it from the canvas and then call shape = nil;