Objective C Blocks: Is there a way to avoid saving the self?

I try to write it as concisely as possible, but it is not easy to describe - so thanks for reading =)

I am the main developer of the Open Source iPhone Framework Sparrow . Sparrow is modeled after the Flash AS3 Library and thus has an event system similar to AS3. This system currently works by specifying a selector, but I would like to expand this system by allowing the use of blocks for event listeners. However, I run into memory management issues.

I will show you a typical case of using events, since they are now being processed.

// init-method of a display object, inheriting from 
// the base event dispatcher class
- (id)init
{
    if (self = [super init])
    {
        // the method 'addEventListener...' is defined in the base class
        [self addEventListener:@selector(onAddedToStage:)
                      atObject:self
                       forType:SP_EVENT_TYPE_ADDED_TO_STAGE];
    }
    return self;
}

// the corresponding event listener
- (void)onAddedToStage:(SPEvent *)event
{
    [self startAnimations]; // call some method of self
}

: , . NSInvocation. NSInvocation , . ( , 99% ).

, , : , dealloc! :

- (id)init
{
    if (self = [super init])
    {
        // [self addEventListener: ...] would somehow cause:
        [self retain]; // (A)
    }
    return self;
}

// the corresponding event listener
- (void)dealloc
{
    // [self removeEventListener...] would cause:
    [self release]; // (B)
    [super dealloc];
}

: init dealloc. , dealloc , !

, "addEventListener..." - . - , ( "" , ), .

, : . - , :

- (id)init
{
    if (self = [super init])
    {
        [self addEventListenerForType:ADDED_TO_STAGE block:^(SPEvent *event)
        {
            [self startAnimations];
        }];
    }
    return self;
}

. : "" - , , , - "", .

, , __block , :

__block id blockSelf = self;
[self addEventListenerForType:ADDED_TO_STAGE block:^(SPEvent *event)
{
    [blockSelf startAnimations];
}];

, , , . API , , . API .

, , , "" - , . I , , , , .

. , .

- , ?
, , - , : -)

+5
2

Apple, , : , , . .

, . API :

[self addEventListenerForType:ADDED_TO_STAGE 
                        block:^(id selfReference, SPEvent *event)

, API (-) . , , , , .

, Apple , release/dealloc . "" NSTimer. - NSRunLoop NSTimer ( ).

+5

, , . , . . /.

, , , . , (), . , , , , , , . (, ), , , .

- , SPEvent, self. , , , , .

+1

All Articles