Utilize an NSBlock within the framework of JavaScriptCore as a property

Is there a way to use NSBlock as a property that is changeable in JavaScript?

@protocol ExportingUser <NSObject, JSExport>

@property (nonatomic, copy) void (^changedName) (void);

@property (nonatomic) NSString* name;

@end

I am trying to call changedName from Obj-C, a function whose definition originates from JavaScript. For example:

user.name = "Peyman"; // this will update the name property in Obj-C.

user.changedName = function() { console.log("yay"); } // but this does not work

I am aware of using JSValue's callWithArguments method, but I would prefer an alternate solution if available.

Edit: Upon further consideration, it seems that the callWithArguments method may not be suitable. This is because objects bound to Objective-C classes are not extendable in JavaScript, meaning any new additions would be ignored.

Answer №1

The information provided in JSValue.h is essential:

//   Objective-C type  |   JavaScript type
// --------------------+---------------------
//         nil         |     undefined
//        NSNull       |        null
//       NSString      |       string
//       NSNumber      |   number, boolean
//     NSDictionary    |   Object object
//       NSArray       |    Array object
//        NSDate       |     Date object
//       NSBlock *     |   Function object *
//          id **      |   Wrapper object **
//        Class ***    | Constructor object ***
//
// * Instances of NSBlock with supported arguments types will be presented as
// callable Function objects to JavaScript. For more details on supported argument
// types, refer to JSExport.h. If a JavaScript Function derived from an Objective-C
// block gets converted back to an Objective-C object, the block itself will be returned.
// All other JavaScript functions will be changed similarly to a JavaScript object of type Object.

It appears that you can use the following code snippet:

@property (nonatomic, copy) JSValue* modifiedName;

Then, when you need to invoke the function:

typedef void (^nameModifiedBlock)(void);

modifiedNameObject = [self.modifiedName toObject];

if ([modifiedNameObject isKindOfClass: NSClassFromString(@"NSBlock")]){
   ((nameModifiedBlock)modifiedNameObject)();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display the Material UI Switch in an active state even when the "checked" value is set to false

While using Material UI Switches with Formik, I've encountered an issue. When I toggle the switch to 'enable,' it automatically sets the value in Formik to "true," and when I toggle it to 'disable,' it sets the value in Formik to " ...

Can you provide the Swift 3 syntax for "M_PI_4" and "M_PI_2"?

While I understand that M_PI is now CGFloat.pi, I am uncertain about the equivalent of M_PI_4. I attempted to calculate it as CGFloat.pi*4 but that turned out to be incorrect. ...

Pause and anticipate user input using the readline module in Node.js

Currently, I am working on a module to gain experience and simplify some code. In one section of the code, I am using readline in a basic way, like this: var x = arkin.question("What is your age? ");. However, the issue is that readline does not wait for t ...

Are there any negatives to turning off create-react-app's SKIP_PREFLIGHT_CHECK option?

After setting up my create-react-app project, I added eslint as a dev dependency. My reasons for doing this include: 1) Running eslint as a pre-commit check using husky and lint-staged 2) Extending CRA's eslint with airbnb and prettier lint configs ...

Save a PHP variable and then use it on an HTML page

Is there a way to preserve the value of LAST_INSERT_ID(), also known as Case_ID, so that it can be accessed in another HTML page? If so, what would be the best approach to achieve this? $query.= "insert into Picture (Case_Pic,Case_ID) values ...

Creating a Rotation Matrix from XYZ Coordinates (Gravity/Acceleration)

For weeks, I've been exploring both Matlab and Apple's documentation on CMRotationMatrix. I discovered that I could easily replicate CMRotationMatrix by calculating it using Roll, Yaw, and Pitch. However, I couldn't find any resources or d ...

How do I improve the efficiency of my JavaScript code to avoid surpassing the time limit on Leetcode?

I'm currently tackling the Two Sum II - Input Array Is Sorted problem on LeetCode, but I keep running into a Time Limit Exceeded issue. This indicates that my code isn't as optimized as it could be and may need a more efficient solution. However, ...

How can you use mouseover events to display a popover and manipulate the div id?

In my scenario, I have multiple div elements and I want to display separate popover for each div. Initially, the popover is not shown on the first mouseover event but works perfectly on subsequent attempts. Below is the code snippet: $(document).read ...

Populating JQuery autocomplete using a PHP array

As a beginner in the world of JavaScript and JQuery, I have been scouring the internet for hours trying to find a solution to my query. My goal is to populate a JQuery autocomplete feature using an array that I have created in PHP. Here is a glimpse of the ...

What could be the reason why the initial console.log is failing to print?

Apologies for the oversight. The !== was a mistake that slipped past me before posting. Thank you for your understanding. I am a beginner in Javascript. I have written this function with winston: function setlogger(log_level = "warn", logfile, scree ...

Improving the efficiency of your if else code in React js

I am looking for a way to optimize my code using a switch statement instead of multiple if-else conditions. How can I achieve this? Here is the current version of my code: handleChange = (selectedkey) => { this.setState({ activeKey: selectedkey } ...

Avoiding mocking a specific module with jest forever

Our codebase heavily relies on underscore in various parts, and I prefer to avoid mocking it. I'm aware that I can use jest.unmock('underscore'); in each test that utilizes underscore. Is there a method to unmock underscore across all tests ...

Using the v-for directive to create sequential lists

I am struggling to display pairs of data from an object based on category using nested v-for loops. The object, categoryArray, contains entries such as {stage 1, red}, {stage 1, blue}, {stage 2, orange}, {stage 3, brown}, {stage 2, green. My desired displ ...

Is it possible for WatchKit's WKInterfaceGroup to function as a Button?

(running iOS8.3, Xcode6.3, OSX10.10.3) Hello there! I am curious to know if it is possible for a WatchKit WKInterfaceGroup to function as a Button? In my watchkit application, I aim to enlarge the touch area for a specific action. I am aware that one ca ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

Explain the operation of recursive function calls in JavaScript

I’ve been working on converting the algorithm found in this Python code snippet into JavaScript. function divide(arr, depth, m) { if (complements.length <= depth) { complements.push(2 ** (depth + 2) + 1); } var complement = comple ...

Repetitively updating the value of a characteristic in Bluetooth Low Energy technology

Stay tuned for more on Electrical Engineering Stackexchange I am looking to constantly write the value of a Bluetooth Low Energy characteristic within a short timeframe, similar to how a mouse operates. The characteristic has a length of 20 bytes with a ...

What is the best way to manage a vuex dispatch response?

Despite feeling like the answer is right in front of me, I'm waving the white flag and seeking suggestions. The challenge lies in my login form that submits to an AWS API and reacts to the result. The trouble starts when the handleSubmit method is tr ...

Guide on declaring package.json during library publication in Angular 6

Building node modules using Angular6 should be a breeze. The Documentation outlines the following steps: ng generate library YOUR-LIBRARY ng build YOUR-LIBRARY --prod cd dist/YOUR-LIBRARY && npm publish By following these steps, a new project wi ...

Different ways to effectively utilize the indexOf method for verifying the presence of an element within an array

In this fun guessing game, I am testing to see if the color entered by the user is in the array list or not. But oddly enough, even when the correct color is input, it keeps saying that it isn't. var guess_input; var target; var colors = ["blue", "cy ...