I am very new to programming and Objective-C and I am trying to work out what is wrong with my code. I have read a bit about blocks but I don\'t know how any of what I have read
The basic problem is that you're using self
within a block. The block is being retained by the object and the block itself retains the object, too. So you have a retain-cycle and thus both will probably never be released because both have a reference pointing towards them. Fortunaly there is a simple workaround:
By using a so-called weak reference to self the block will no longer retain the object. The object then can later be released which will release the block (set MyClass
to the appropriate type):
// before your block
__weak MyObject *weakSelf = self;
Inside your block you now can use weakSelf
instead of self
. Note that this is only for iOS 5 using ARC.
Looking at this there is also a very good long explanation on How do I avoid capturing self in blocks when implementing an API? which also describes how to avoid this on iOS 4 and without ARC.