Providing my own objects for "make new" in my scriptable application - objective-c

This is a question about implementing a scriptable application using Cocoa Scripting.
My app's scriptable application object contains elements of a custom class, let call it flower.
In the .sdef file, the Cocoa class for flower is specified as ScriptableFlower.
In Applescript, one can now write:
tell app "myapp"
get flowers
end tell
My code provides an accessor function for retrieving flowers: -(NSArray*)flowers.
Now, I like to implement a way to add new flowers, so that one can write:
tell app "myapp"
make new flower
end tell
The default behavior for this, with the default Core suite handler for "make" using NSCreateCommand, is as follows:
The scripting engine will fetch the current array of flowers by calling my flowers function, then instantiate a new Cocoa object of class ScriptableFlower, and then call setFlowers:(NSArray*) with an array that contains my original objects plus the newly created one.
However, this is not good for my application: I cannot allow the scripting engine to create objects of my scriptable classes at will.
Instead, I need to be the one instantiating them.
A half-way solution would be to implement the default -(id)init method and then detect if it's called by me - if not, I can take the extra steps. But that's not clean. I rather do not let the scripting engine create new objects at all but rather provide them myself as I may have the object "somewhere" already prepared.
Is there some provision in Cocoa Scripting that leads to it calling me whenever it wants me to create a new scriptable object?
Update
To clarify: The Cocoa Scripting docs explains that one can implement special insertion handlers (insertObject:in<Key>AtIndex:)so that one doesn't have to take the entire NSArray, but that still leads to the scripting engine to create the object. I need to be asked to create the object instead, though.

The file NSObjectScripting.h provides a function for this:
- (id)newScriptingObjectOfClass:(Class)objectClass forValueForKey:(NSString *)key withContentsValue:(id)contentsValue properties:(NSDictionary *)properties;
It's available since OS X 10.5 and documented as follow:
Create a new instance of a scriptable class to be inserted into the relationship identified by the key, set the contentsValue and properties of it, and return it. Or return nil for failure. The contentsValue and properties are derived from the "with contents" and "with properties" parameters of a Make command. The contentsValue may be nil. When this method is invoked by Cocoa neither the contentsValue nor the properties will have yet been coerced using scripting key-value coding's -coerceValue:forKey: method. In .sdef-declared scriptability the types of the passed-in objects reliably match the relevant .sdef declarations however.

One option is to subclass NSCreateCommand and implement your own logic.

Related

Adding new members and extending methods in an external API interface

I am building an VB.NET application in Visual Studio using SOLIDWORKS API - my application connects to SOLIDWORKS application via COM, and performs some actions in it using various API calls. The API is accessed by adding project references to SOLIDWORKS .dll files. These files must be embedded to the executable of my application for legal reasons.
This question is not specific to that API, but I will try to explain what I want to do. There is a SOLIDWORKS API interface called Body2 that governs manipulation of model objects (bodies) in 3D space. For example, Body2 interface provides a method ApplyTransform that allows moving or rotating a certain body by applying a MathTransform (a transform matrix) to it:
ModelBody.ApplyTransform(rotationMatrix) 'rotates the body
Now, the Body2 objects do not store these transformation matrices - they are applied and forgotten. However, in my application, I need to persistently store that information, so that at some point, I can reverse all transformations, and return the body to it's original position.
Therefore, I want to extend the Body2 interface by adding a new property to it, called "CombinedTransformMatrix", so that every time I call ApplyTransform, I could also update the value of this property, for example:
ModelBody.ApplyTransform(rotationMatrix)
ModelBody.CombinedTransformMatrix.Multiply(rotationMatrix)
ModelBody.ApplyTransform(translationMatrix)
ModelBody.CombinedTransformMatrix.Multiply(translationMatrix)
And when I finally want to return the body to it's original position, I could call:
ModelBody.ApplyTransform(ModelBody.CombinedTransformMatrix.Inverse)
ModelBody.CombinedTransformMatrix = New MathTransform 'reset matrix
Ideally, it would be really nice to also extend the ApplyTransform method, so that it would update the CombinedTransformMatrix automatically, for example:
Overrides Function ApplyTransform(Xform As MathTransform) As Boolean
'Do whatever SOLIDWORKS does in this function
'My additional code:
Me.CombinedTransformMatrix.Multiply(Xform)
End function
(I know I should do an extension rather than an override, but I don't know how)
If this is possible, then I could simplify the code for the body transformations, as the CombinedTransformMatrix would update automatically:
'Rotate and move
ModelBody.ApplyTransform(rotationMatrix)
ModelBody.ApplyTransform(translationMatrix)
'Return to original position
ModelBody.ApplyTransform(ModelBody.CombinedTransformMatrix.Inverse)
ModelBody.CombinedTransformMatrix = New MathTransform 'reset matrix
I would very much prefer this kind of a solution instead of creating some derived class from Body2, or making some kind of a wrapper class that stores CombinedTransformMatrix outside the Body2 object. I want to store that bit inside the object itself. As for derived class, Visual Studio doesn't even allow me to inherit from Body2 - says "'Body2Class' is not allowed when its assembly is configured to embed interop types.". And I must embed these .dll files because otherwise I would have to ship them along the .exe of my application, which is legally prohibited by SOLIDWORKS.
Is what I want possible? Can I add that CombinedTransformMatrix to the Body2 interface without creating a derived class? And is it possible to extend that ApplyTransform method with my additional code without knowing how that method is implemented?
If not, what is the next best solution to achieve what I want? Like I said, I would very much like to avoid wrappers or additional variables outside of Body2, because there will be lots of these Body2 objects, they will persist throughout the application's lifetime, each will have a different transformation, so having to store their transformation information outside themselves would seriously complicate my code.
There is no universal way of doing this. You can maintain the separate dictionary with your COM object (e.g. IBody2 in this case) to be a key and the additional parameters (tags) to be a value. You will need to manually update the dictionary to remove the data when the pointer is destroyed. There are however some specific SW interfaces that do have some ways to associate custom data (similar to tags). For instance, IBody2 has the IBody2::AddPropertyExtension2 which allows associating custom data with the body itself, IEntity has the IEntity::CreateStringAttributeDefinition (note, this is not documented method) etc.
But there is no something like universal System::Windows::Forms::Tag property for Windows Controls or Dependency Property for DependencyObjects exists for COM classes.

What is the difference between functions that start with "allocate", "create", "initialize" and so on

When it comes to naming a function, what are the main differences between the following words:
"allocate", "create", "initialize", "instantiate", "make", "build", "add" and "insert".
When should I use each word?
Thank you in advance :)
I associate allocate, create, instantiate and make with the creation of a new object whereas initialize is more associated with setting initial values. The words add and insert are used for functions or methods which add new elements to some collection, like a list or a tree. When I read build I think of a process for compiling and linking software source code.
I summarize the existing usage of allocate, initialize, instantiate, make, build, create, add, insert, and two more I needed in this comparison: put and update, below.
allocate; synonyms alloc (C); used for "allocating" or alloting space in memory
initialize; synonyms init, __init__ (python)`; used for instantiating an object from a class or prototype
instantiate;; there's not a super strong case for this anywhere, but you're welcome to look
make;; in a shell scripting language (like bash), make is traditionally a command that manages compilation of different parts of a C or C++ project. in go, make is a built-in function that offers functional syntax for instantiating an object of type slice, map, or chan.
build;; a lot of Makefiles will support this method because it falls in line with "building" or compiling a project.
create; synonyms insert and POST (REST); used for creating a new web resource without an id. Errors if the web resource already exists.
put; synonyms add, sadd (redis), zadd (redis), set (redis), PUT (REST); creates a web resource by id. Updates the resource completely if it already exists.
update; synonyms hset (redis), PATCH (REST); updates a web resource by id. Some implementations throw, others create if resource does not exist.
I leave how you should be using these words to your discretion.

In Objective-C, what is the standard way of extending and augmenting the behaviour of init?

Categories are used in Objective-C to implement extensions onto existing classes.
This is great for supplying new methods that could be used, but does not necessarily help augmenting behaviours of the existing class methods.
In particular, I'm interested in extending init methods and customize them such that necessary set up for my category is performed at object initialization time. If you must know, these are ReactiveCocoa signals that I'd like set up once per object lifetime. This ideally should go in init.
The obvious way of doing this is to call a setUpXYZExtension method defined in the category directly from init. However, this means the main source file now has knowledge of the extension. i.e. deleting the extension source file will lead to a compile error because the method setUpXYZExtension will not be found.
Is there a potentially neater way of doing this, such that when the category's source file is deleted, there is no compile error?
Not sure about this being standard but you can look at method swizzling. Swizzling allows you to either extend or exchange the implementation of methods of current classes.
http://nshipster.com/method-swizzling/

Custom performance profiler for Objective C

I want to create a simple to use and lightweight performance profile framework for Objective C. My goal is to measure the bottlenecks of my application.
Just to mention that I am not a beginner and I am aware of Instruments/Time Profiler. This is not what I am looking for. Time Profiler is a great tool but is too developer oriented. I want a framework that can collect performance data from a QA or pre production users and even incorporate in a real production environment to gather the real data.
The main part of this framework is the ability to measure how much time was spent in Objective C message (I am going to profile only Objective C messages).
The easiest way is to start timer in the beginning of a message and stop it at the end. It is the simplest way but its disadvantage is that it is to tedious and error prone - if any message has more than 1 return path then it will require to add the "stop timer" code before each return.
I am thinking of using method swizzling (just to note that I am aware that Apple are not happy with method swizzling but these profiled builds will be used internally only - will not be uploaded on the App Store).
My idea is to mark each message I want to profile and to generate automatically code for the method swizzling method (maybe using macros). When started, the application will swizzle the original selector with the generated one. The generated one will just start a timer, will call the original method and then will stop the timer. So in general the swizzled method will be just a wrapper of the original one.
One of the problems of the above idea is that I cannot think of an easy way how to automatically generate the methods to use for swizzling.
So I greatly will appreciate if anyone has any ideas how to automate the whole process. The perfect scenario is just to write one line of code anywhere mentioning the class and the selector I want to profile and the rest to be generated automatically.
Also will be very thankful if you have any other idea (beside method swizzling) of how to measure the performance.
I came up with a solution that works for me pretty well. First just to clarify that I was unable to find out an easy (and performance fast) way to automatically generate the appropriate swizzled methods for arbitrary selectors (i.e. with arbitrary arguments and return value) using only the selector name. So I had to add the arguments types and the return value for each selector, not only the selector name. In reality it should be relatively easy to create a small tool that would be able to parse all source files and detect automatically what are the arguments types and the returned value of the selector which we want to profile (and prepare the swizzled methods) but right now I don't need such an automated solution.
So right now my solution includes the above ideas for method swizzling, some C++ code and macros to automate and minimize some coding.
First here is the simple C++ class that measures time
class PerfTimer
{
public:
PerfTimer(PerfProfiledDataCounter* perfProfiledDataCounter);
~PerfTimer();
private:
uint64_t _startTime;
PerfProfiledDataCounter* _perfProfiledDataCounter;
};
I am using C++ to use that the destructor will be executed when object has exited the current scope. The idea is to create PerfTimer in the beginning of each swizzled method and it will take care of measuring the elapsed time for this method
The PerfProfiledDataCounter is a simple struct that counts the number of execution and the whole elapsed time (so it may find out what is the average time spent).
Also I am creating for each class I'd like profile, a category named "__Performance_Profiler_Category" and to conforms to "__Performance_Profiler_Marker" protocol. For easier creating I am using some macros that automatically create such categories. Also I have a set of macros that take selector name, return type and arguments type and create selectors for each selector name.
For all of the above tasks, I've created a set of macros to help me. Also I have a single file with .mm extension to register all classes and all selectors I'd like to profile. On app start, I am using the runtime to retrieve all classes that conforms to "__Performance_Profiler_Marker" protocol (i.e. the registered ones) and search for selectors that are marked for profiling (these selectors starts with predefined prefix). Note that this .mm file is the only file that needs .mm extension and there is no need to change file extension for each class I want to profile.
Afterwards the code swizzles the original selectors with the profiled ones. In each profiled one, I just create PerfTimer and call the swizzled method.
In brief that is my idea which turned out to work pretty smoothly.

What is the use of reflection in Java/C# etc [duplicate]

This question already has answers here:
What is reflection and why is it useful?
(23 answers)
Closed 6 years ago.
I was just curious, why should we use reflection in the first place?
// Without reflection
Foo foo = new Foo();
foo.hello();
// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();
Method method = cls.getMethod("hello", null);
method.invoke(foo, null);
We can simply create an object and call the class's method, but why do the same using forName, newInstance and getMthod functions?
To make everything dynamic?
Simply put: because sometimes you don't know either the "Foo" or "hello" parts at compile time.
The vast majority of the time you do know this, so it's not worth using reflection. Just occasionally, however, you don't - and at that point, reflection is all you can turn to.
As an example, protocol buffers allows you to generate code which either contains full statically-typed code for reading and writing messages, or it generates just enough so that the rest can be done by reflection: in the reflection case, the load/save code has to get and set properties via reflection - it knows the names of the properties involved due to the message descriptor. This is much (much) slower but results in considerably less code being generated.
Another example would be dependency injection, where the names of the types used for the dependencies are often provided in configuration files: the DI framework then has to use reflection to construct all the components involved, finding constructors and/or properties along the way.
It is used whenever you (=your method/your class) doesn't know at compile time the type should instantiate or the method it should invoke.
Also, many frameworks use reflection to analyze and use your objects. For example:
hibernate/nhibernate (and any object-relational mapper) use reflection to inspect all the properties of your classes so that it is able to update them or use them when executing database operations
you may want to make it configurable which method of a user-defined class is executed by default by your application. The configured value is String, and you can get the target class, get the method that has the configured name, and invoke it, without knowing it at compile time.
parsing annotations is done by reflection
A typical usage is a plug-in mechanism, which supports classes (usually implementations of interfaces) that are unknown at compile time.
You can use reflection for automating any process that could usefully use a list of the object's methods and/or properties. If you've ever spent time writing code that does roughly the same thing on each of an object's fields in turn -- the obvious way of saving and loading data often works like that -- then that's something reflection could do for you automatically.
The most common applications are probably these three:
Serialization (see, e.g., .NET's XmlSerializer)
Generation of widgets for editing objects' properties (e.g., Xcode's Interface Builder, .NET's dialog designer)
Factories that create objects with arbitrary dependencies by examining the classes for constructors and supplying suitable objects on creation (e.g., any dependency injection framework)
Using reflection, you can very easily write configurations that detail methods/fields in text, and the framework using these can read a text description of the field and find the real corresponding field.
e.g. JXPath allows you to navigate objects like this:
//company[#name='Sun']/address
so JXPath will look for a method getCompany() (corresponding to company), a field in that called name etc.
You'll find this in lots of frameworks in Java e.g. JavaBeans, Spring etc.
It's useful for things like serialization and object-relational mapping. You can write a generic function to serialize an object by using reflection to get all of an object's properties. In C++, you'd have to write a separate function for every class.
I have used it in some validation classes before, where I passed a large, complex data structure in the constructor and then ran a zillion (couple hundred really) methods to check the validity of the data. All of my validation methods were private and returned booleans so I made one "validate" method you could call which used reflection to invoke all the private methods in the class than returned booleans.
This made the validate method more concise (didn't need to enumerate each little method) and garuanteed all the methods were being run (e.g. someone writes a new validation rule and forgets to call it in the main method).
After changing to use reflection I didn't notice any meaningful loss in performance, and the code was easier to maintain.
in addition to Jons answer, another usage is to be able to "dip your toe in the water" to test if a given facility is present in the JVM.
Under OS X a java application looks nicer if some Apple-provided classes are called. The easiest way to test if these classes are present, is to test with reflection first
some times you need to create a object of class on fly or from some other place not a java code (e.g jsp). at that time reflection is useful.