I want to persist a block inside core data NSManagedObject if it's possible. I have an inherited class from NSManagedObject.
This class have a block to satisfy some asynchronous calls. I tried to store the block as a Transformable and Transient attribute. when I try to invoke the block before load my NSManagedObject I have a bad memory access "EXC_BAD_ACCESS"
.
If I don't check the transformable flag I have an exception similar to this:
-[__NSStackBlock__ encodeWithCoder:]: unrecognized selector sent to instance 0xbfffd930
I'm new in iOS. I'm working under iOS 5 SDK with ARC enabled. This is a extract from my code:
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@class ModbusRegister, Board;
typedef void (^DataBlockType)(NSArray *listRegister);
@interface EnergyEntry : NSManagedObject
- (void)invokeWithData: (NSArray *)listRegister;
@property (nonatomic, copy) DataBlockType datablock;
@end
#import "EnergyEntry.h"
@implementation EnergyEntry
@dynamic datablock;
- (void)invokeWithData: (NSArray *)listRegister{
self.datablock(listRegister);
}
@end
When I tried to store the block:
[energyEntry setValue:@"Energía activa" forKey:@"name"];
[energyEntry setValue:[NSNumber numberWithDouble:0] forKey:@"value"];
[energyEntry setValue:currentBoard forKey:@"board"];
[energyEntry setValue:^(NSArray *listRegister){
//...my block operations to store
} forKey:@"datablock"];
Finally when I invoke the block and the error is fired:
NSArray *listRegister=... //my ready array
[energyEntry invokeWithData:listRegister];
You can't store a block as a transformable type. According to Apple documentation transformable object has to be convertible to NSData. Block can't be converted to NSData because it is a compiler's reference to compiled code, not some data that can be moved around.
Just a note, that the block is like an anonymous method. You can call it many times, each time with a different parameter. So nothing is stopping you from storing the block once and calling it many times in each asynchronous call separately. If you think that you need many blocks then most likely you just need to store the data that should be passed to each block invocation.