Search code examples
iosc4

Communication between objects - C4Framework


I'm working with the alpha release of C4 and I'm trying to send messages between objects but i cant make it work. Im trying with a really simple example but i cant make it work... I've tried this:

[ashape listenFor:@"touch" from:anothershape andRunMethod:@"receive"];

but I dont get any messages or nothing...

this is what i have:

#import "MyShape.h"

@implementation MyShape
-(void)receive {
    C4Log(@"this button");
}
@end

Solution

  • I see one main problem with the code you posted.

    By default, all visible objects in C4 post a touchesBegan notification when they are tapped. In your code you are listening for @"touch" whereas @"touchesBegan" is what you should be listening for.

    The changing color method is easy to implement... In your MyShape.m file, you can use a method like:

    -(void)changeColor {
        CGFloat red = RGBToFloat([C4Math randomInt:255]);
        CGFloat green = RGBToFloat([C4Math randomInt:255]);
        CGFloat blue = RGBToFloat([C4Math randomInt:255]);
    
        self.fillColor = [UIColor colorWithRed:red green:green blue:blue alpha:1.0f];
    }
    

    In order to get things working nicely, your C4WorkSpace.m should look like:

    #import "C4WorkSpace.h"
    #import "MyShape.h"
    
    @implementation C4WorkSpace {
        MyShape *s1, *s2;
    }
    
    -(void)setup {
        s1 = [MyShape new];
        s2 = [MyShape new];
    
        [s1 rect:CGRectMake(100, 100, 100, 100)];
        [s2 rect:CGRectMake(300, 100, 100, 100)];
    
        [s1 listenFor:@"touchesBegan" fromObject:s2 andRunMethod:@"changeColor"];
        [s2 listenFor:@"touchesBegan" fromObject:s1 andRunMethod:@"changeColor"];
    
        [self.canvas addShape:s1];
        [self.canvas addShape:s2];
    }
    @end