iosobjective-ctheos

Objective-C/THEOS - Is it possible to save a NSMallocBlock?


When hooking a certain method a parameter is passed through that is a NSMallocBlock. I need to save this value to use it later when recalling the method from my code. I tried to save it to a user default, but this causes the program to crash. Is there anyway to save the object or recreate it later?


Solution

  • Natively, blocks cannot be persisted.

    @interface AwesomeClass : NSObject
    
    @property (nonatomic, copy, nullability) returnType (^blockName)(parameterTypes);
    
    @end
    

    (block syntax via How Do I Declare A Block in Objective-C?)

    The will allow you to keep a reference to your block for later in your program's execution. Note that you should always use copy as most blocks are initialised on the stack. Weird things happen if you don't.

    As an aside, NSUserDefaults is designed for persisting small amounts of data between executions of your program. -[NSUserDefaults setObject:forKey:] only supports NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. It will generally crash if you try to set it to any other type of object. More details can be found here: setObject:forKey: - NSUserDefaults | Apple Developer Documentation.