Reputation: 788
I am new to blocks. I want to create a iVar NSMutableArray which I can access inside a block method.Can someone please tell me how to declare it using _block keyword?`
@interface ViewController : UIViewController
{
__block NSMutableArray *array;
}
@property (nonatomic, weak) NSMutableArray *array;
Upvotes: 3
Views: 783
Reputation: 299265
You should generally not be accessing ivars from within anything but init
and dealloc
. So there's almost never a reason to access an ivar directly from within a block. Instead, use accessors on the object that owns the ivar (often self
).
For multi-threaded blocks this will look something like this:
__weak id weakself = self;
[obj doSomethingWithBlock:^{
id strongself = weakself;
strongself.array = nil; // Can't safely read from the array here without more code.
}];
If this is not a multi-threaded operation, then you can just do this:
__weak id weakself = self;
[obj doSomethingWithBlock:^{
NSLog(@"%@", weakself.array[0]);
}];
If there is no danger of a retain loop (because the block executes immediately on this thread), you can do this even more simply:
[obj doSomethingWithBlock:^{
NSLog(@"%@", self.array[0]);
}];
Upvotes: 0
Reputation: 7250
You don't need to set the __block
in front of your iVar.
According to : http://developer.apple.com/library/ios/#documentation/cocoa/conceptual/Blocks/Articles/bxVariables.html
When a block is copied, it creates strong references to object variables used within the block. If you use a block within the implementation of a method:
- If you access an instance variable by reference, a strong reference is made to self;
- If you access an instance variable by value, a strong reference is made to the variable.
Upvotes: 3