Search code examples
iosobjective-c-blocksprivate-methods

Blocks vs private methods?


What are the disadvantages of using a block to define a private method within a method, instead of using a real private method? Is there any apart from not being able to call the method from somewhere else?

Example:

-(NSDictionary*)serialize
{   
    NSMutableDictionary* serialization = [NSMutableDictionary dictionary];

    TwoArgumentsBlockType serializeItemBlock = ^void(MyItemClass* item, NSString* identifier)
    {       
        if (item)
        {
            // serialization code
        }
    };

    serializeItemBlock(self.someItem1, kSomeIdentifier1);
    serializeItemBlock(self.someItem2, kSomeIdentifier2);
    serializeItemBlock(self.someItem3, kSomeIdentifier3);
    serializeItemBlock(self.someItem4, kSomeIdentifier4);
    serializeItemBlock(self.someItem5, kSomeIdentifier5);
    serializeItemBlock(self.someItem6, kSomeIdentifier6);
    serializeItemBlock(self.someItem7, kSomeIdentifier7);
    serializeItemBlock(self.someItem8, kSomeIdentifier8);
    serializeItemBlock(self.someItem9, kSomeIdentifier9);
    serializeItemBlock(self.someItem10, kSomeIdentifier10);
    serializeItemBlock(self.someItem11, kSomeIdentifier11);

    return serialization;
}

Solution

  • Clarity of the code is important.

    Methods allow you to encapsulate entire sections of code apart from each other, and can make it easier to read..

    Another reason to choose private methods over blocks is memory management. This is far to big of a topic to discuss here, but sufficed to say that blocks are weird in the memory management, and don't act like any other code structure in that regard.