Is it possible to change an Objective-C object to a different type at runtime? - objective-c

I have a situation where I want to create an object before I know what type it will eventually be. I know what its superclass will be, and want to temporarily create a concrete instance of that superclass and allow other objects to use it in that form until its "true" class can be created.
I realize this is pretty crazy and I don't have too high expectations that this is possible, but if I could do this it would be amazing. I know the Obj-C runtime has some pretty powerful features so thought it was at least worth asking.
I've looked into object_setClass, but while this appears to allow you technically change the class of an object at runtime, it doesn't allow you to actually reallocate a new instance, complete with its own ivars, at the address of the original instance, which is really what I need as I don't know specifically what the final class will be (it needs to work with any custom subclass).
Background: My intention is to provide a placeholder object that will allow external code to register dependencies and/or hold a reference to, such that when the object is eventually filled-in, those external dependencies will still hold and they won't have to correct their references.

You could try using NSProxy and ultimately proxying to the "real" underlying object you need.

Related

extending objects at run-time via categories?

Objective-C’s objects are pretty flexible when compared to similar languages like C++ and can be extended at runtime via Categories or through runtime functions.
Any idea what this sentence means? I am relatively new to Objective-C
While technically true, it may be confusing to the reader to call category extension "at runtime." As Justin Meiners explains, categories allow you to add additional methods to an existing class without requiring access to the existing class's source code. The use of categories is fairly common in Objective-C, though there are some dangers. If two different categories add the same method to the same class, then the behavior is undefined. Since you cannot know whether some other part of the system (perhaps even a system library) adds a category method, you typically must add a prefix to prevent collisions (for example rather than swappedString, a better name would likely be something like rnc_swappedString if this were part of RNCryptor for instance.)
As I said, it is technically true that categories are added at runtime, but from the programmer's point of view, categories are written as though just part of the class, so most people think of them as being a compile-time choice. It is very rare to decide at runtime whether to add a category method or not.
As a beginner, you should be aware of categories, but slow to create new ones. Creating categories is a somewhat intermediate-level skill. It's not something to avoid, but not something you'll use every day. It's very easy to overuse them. See Justin's link for more information.
On the other hand, "runtime functions" really do add new functionality to existing classes or even specific objects at runtime, and are completely under the control of code. You can, at runtime, modify a class such that it responds to a method it didn't previously respond to. You can even generate entirely new classes at runtime that did not exist when the program was compiled, and you can change the class of existing objects. (This is exactly how Key-Value Observation is implemented.)
Modifying classes and objects using the runtime is an advanced skill. You should not even consider using these techniques in production code until you have significant experience. And when you have that experience, it will tell you that you very seldom what to do this anyway. You will know the runtime functions because they are C-based, with names like method_exchangeImplmentations. You won't mistake them for normal ObjC (and you generally have to import objc/runtime.h to get to them.)
There is a middle-ground that bleeds into runtime manipulation called message forwarding and dynamic message resolution. This is often used for proxy objects, and is implemented with -forwardingTargetForSelector, +resolveInstanceMethod, and some similar methods. These are tools that allow classes to modify themselves at runtime, and is much less dangerous than modifying other classes (i.e. "swizzling").
It's also important to consider how all of this translates to Swift. In general, Swift has discouraged and restricted the use of runtime class manipulation, but it embraces (and improves) category-like extensions. By the time you're experienced enough to dig into the runtime, you will likely find it an even more obscure skill than it is today. But you will use extensions (Swift's version of categories) in every program.
A category allows you to add functionality to an existing class that you do not have access to source code for (System frameworks, 3rd party APIs etc). This functionality is possible by adding methods to a class at runtime.
For example lets say I wanted to add a method to NSString that swapped uppercase and lowercase letters called -swappedString. In static languages (such as C++), extending classes like this is more difficult. I would have to create a subclass of NSString (or a helper function). While my own code could take advantage of my subclass, any instance created in a library would not use my subclass and would not have my method.
Using categories I can extend any class, such as adding a -swappedString method and use it on any instance of the class, such asNSString transparently [anyString swappedString];.
You can learn more details from Apple's Docs

is it acceptable to provide an API that is undefined a large part of the time?

Given some type as follows:
class Thing {
getInfo();
isRemoteThing();
getRemoteLocation();
}
The getRemoteLocation() method only has a defined result if isRemoteThing() returns true. Given that most Things are not remote, is this an acceptable API? The other option I see is to provide a RemoteThing subclass, but then the user needs a way to cast a Thing to a RemoteThing if necessary, which just seems to add a level of indirection to the problem.
Having an interface include members which are usable on some objects that implement the interface but not all of them, and also includes a query method to say which interface members will be useful, is a good pattern in cases where something is gained by it.
Examples of reasons where it can be useful:
If it's likely than an interface member will be useful on some objects but not other instances of the same type, this pattern may be the only one that makes sense.
If it's likely that a consumer may hold references to a variety of objects implementing the interface, some of which support a particular member and some of which do not, and if it's likely that someone with such a collection would want to use the member on those instances which support it, such usage will be more convenient if all objects implement an interface including the member, than if some do and some don't. This is especially true for interface members like IDisposable.Dispose whose purpose is to notify the implementation of something it may or may not care about (e.g. that nobody needs it anymore and it may be abandoned without further notice), and ask it to do whatever it needs to as a consequence (in many cases nothing). Blindly calling Dispose on an IEnumerable<T> is faster than checking whether an implementation of IEnumerable also implements IDisposable. Not only the unconditional call faster than checking for IDisposable and then calling it--it's faster than checking whether an object implements IDisposable and finding out that it doesn't.
In some cases, a consumer may use a field to hold different kinds of things at different times. As an example, it may be useful to have a field which at some times will hold the only extant reference to a mutable object, and at other times will hold a possibly-shared reference to an immutable object. If the type of the field includes mutating methods (which may or may not work) as well as a means of creating a new mutable instance with data copied from an immutable one, code which receives an object and might want to mutate the data can store a reference to the passed-in object. If and when it wants to mutate the data, it can overwrite the field with a reference to a mutable copy; if it never ends up having to mutate the data, however, it can simply use the passed-in immutable object and never bother copying it.
The biggest disadvantage of having interfaces include members that aren't always useful is that it imposes more work on the implementers. Thus, people writing interfaces should only include members whose existence could significantly benefit at least some consumers of almost every class implementing the interface.
Why should this not be acceptable? It should, however, be clearly documented. If you look at the .net class libraries or the JDK, there are collection interfaces defining methods to add or delete items, but there are unmodifiable classes implementing these interfaces. It is a good idea in this case - as you did - to provide a method to query the object if it has some capabilities, as this helps you avoid exceptions in the case that the method is not appropriate.
OTOH, if this is an API, it might be more appropriate to use an interface than a class.

OOP: Should setters be private?

When writing getter/setters in classes, should the setters be private methods?
It might seem a bit redundant to have to write another method to set a variable but it seems like that might allow for a more maintainable code structure.
Setter is a method that is suppose to allow modifying internal state of an object without exposing that object directly. We can later include validation or other logic inside setter.
If your setter is private, you are missing the point. It's like having a door in your house that is always closed and doesn't even allow opening. Also inside the class you can simply access the field directly, why would you use a setter there?
Of course the real question is: should we have setters at all? The typical class these days holds a bunch of fields, auto-generated getters/setters and no logic. This is hardly a class. It's just a structure with awkward way of accessing elements. But that's not what you are asking for.
In General, I don't recommend "private" access for any member, maybe "protected". Usually, you or other programmer may require it in a descendant class.
Long Boring Descriptive Answer
Now, for accessors ("getters & setters"), its also depends on the syntax and implementation of properties on the programming language.
For Example, C++, or Java, I consider not have "real properties", and accesors, maybe required to have the same scope as the properties. (Unless using a template for properties).
C# & Delphi (Lazarus) have properties implemented, but, I don't like the way C# declare the accesors.
There are cases, where you may want a property not to be public, maybe "protected" or "package protected", and its accesors, the same access than the property.
I just work in some code in Object Pascal. Most properties where "public", and its accesors "protected", but, want to migrate that code to c++ or Java, so, I make the accesors "public", as well.
Quick Short Answer
Same access as the property, but, depends on the syntax of properties.
They should be public, if the intent is to allow them to be manipulated from an external object. That is the point of POJO implementation. (http://en.wikipedia.org/wiki/Plain_Old_Java_Object)
If you're looking to implement some other pattern, perhaps looking at the docs on Java Access Modifiers should be your first stop (http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html)
Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.
However there might be some cases where you want to restrict access to your data just to instances of the same class, but you still want to retain some control over the access to the data for whatever reason (bookkeeping, locking etc.) - in that case having private (or protected) setters/getters makes sense (from both code reuse and safety POV). However, you can't rely on the compiler to catch you doing something wrong then.

"Finding" an object instance of a known class?

My first post here (anywhere for that matter!), re. Cocoa/Obj-C (I'm NOT up to speed on either, please be patient!). I hope I haven't missed the answer already, I did try to find it.
I'm an old-school procedural dog (haven't done any programming since the mid 80's, so I probably just can't even learn new tricks), but OOP has my head spinning! My question is:
is there any means at all to
"discover/find/identify" an instance
of an object of a known class, given
that some OTHER unknown process
instantiated it?
eg. somthing that would accomplish this scenario:
(id) anObj = [someTarget getMostRecentInstanceOf:[aKnownClass class]];
for that matter, "getAnyInstance" or "getAllInstances" might do the trick too.
Background: I'm trying to write a plugin for a commercial application, so much of the heavy lifting is being done by the app, behind the scenes.
I have the SDK & header files, I know what class the object is, and what method I need to call (it has only instance methods), I just can't identify the object for targetting.
I've spent untold hours and days going over Apples documentation, tutorials and lots of example/sample code on the web (including here at Stack Overflow), and come up empty. Seems that everything requires a known target object to work, and I just don't have one.
Since I may not be expressing my problem as clearly as needed, I've put up a web page, with diagram & working sample pages to illustrate:
http://www.nulltime.com/svtest/index.html
Any help or guidance will be appreciated! Thanks.
I have the SDK & header files, I know what class the object is, and what method I need to call (it has only instance methods), I just can't identify the object for targetting.
If this is a publicly declared class with publicly declared instance methods (i.e., you have the header for the class and it has instance methods in it), there is probably a way in this application's API to get an instance of the class. Either you are meant to create one yourself, or the application has one (or more) and provides a way to get it (or them). Look at both the header for the class in question and the other headers.
I initially said “there must be a way…”, but I changed it, because there is an alternative reason why the header would have instance methods: The application developer does not intend those instance methods for plug-in use (and didn't mark them appropriately), or did not mean to include that header in the application/SDK (they included it by accident). You may want to ask the application developer for guidance.
If it is not a publicly declared class or its instance methods are not publicly declared, then the application does not support you working with instances of the class. Doing so is a breach of the API contract—not a legal contract, but the expectations that the application has of its plug-ins. If you breach the API contract, you will cause unexpected behavior, either now (not necessarily on your own machine/in your own tests) or in the future.
If the class's public declaration contains only class methods, then perhaps what you're after is not an instance at all—you're supposed to send those messages to the class itself.
This is not possible without having you register each instance in a dictionary as it is created. I.e., override some common factory method at a higher level which does this bookkeeping work. This will fall down when you use delegates that you may not control though, keep that in mind.
I do question the need to even do this at all, but I don't know your problem as well as I perhaps would need to, to recommend a different, more apt way of accomplishing the actual task at hand.
Just as a corollary to the above; I did look at the runtime to see if there was anything that I actually forgot about, but there is not. So my above statement with regards to you requiring to do that bookkeeping yourself, still holds I'm afraid.
Edit:
Based on your diagram (my apologies, just noticed the link after I posted this answer); I would suggest that if you control the classes that are being returned to you, just add a property to them. I.e., add a "name" property that you can set and keep unique. Then just pass the message to each instance, checking whether or not that object is the one you want. It's not particularly clever or anything like that, but it should work for your purposes.

Abstract design / patterns question

I had a bunch of objects which were responsible for their own construction (get properties from network message, then build). By construction I mean setting frame sizes, colours, that sort of thing, not literal object construction.
The code got really bloated and messy when I started adding conditions to control the building algorithm, so I decided to separate the algorithm to into a "Builder" class, which essentially gets the properties of the object, works out what needs to be done and then applies the changes to the object.
The advantage to having the builder algorithm separate is that I can wrap/decorate it, or override it completely. The object itself doesn't need to worry about how it is built, it just creates a builder and 'decorates' the builder with extra the functionality that it needs to get the job done.
I am quite happy with this approach except for one thing... Because my Builder does not inherit from the object itself (object is large and I want run-time customisation), I have to expose a lot of internal properties of the object.
It's like employing a builder to rebuild your house. He isn't a house himself but he needs access to the internal details, he can't do anything by looking through the windows. I don't want to open my house up to everyone, just the builder.
I know objects are supposed to look after themselves, and in an ideal world my object (house) would build itself, but I am refactoring the build portion of this object only, and I need a way to apply building algorithms dynamically, and I hate opening up my objects with getters and setters just for the sake of the Builder.
I should mention I'm working in Obj-C++ so lack friend classes or internal classes. If the explanation was too abstract I'd be happy to clarify with something a little more concrete. Mostly just looking for ideas or advice about what to do in this kind of situation.
Cheers folks,
Sam
EDIT: is it a good approach to declare a
interface House(StuffTheBuilderNeedsAccessTo)
category inside Builder.h ? That way I suppose I could declare the properties the builder needs and put synthesizers inside House.mm. Nobody would have access to the properties unless they included the Builder header....
That's all I can think of!
I would suggest using Factory pattern to build the object.
You can search for "Factory" on SO and you'll a get a no. of questions related to it.
Also see the Builder pattern.
You might want to consider using a delegate. Add a delegate method (and a protocol for the supported methods) to your class. The objects of the Builder class can be used as delegates.
The delegate can implement methods like calculateFrameSize (which returns a frame size) etc. The returned value of the delegate can be stored as an ivar. This way the implementation details of your class remain hidden. You are just outsourcing part the logic.
There is in fact a design pattern called, suitable enough, Builder which does tries to solve the problem with creating different configurations for a certain class. Check that out. Maybe it can give you some ideas?
But the underlying problem is still there; the builder needs to have access to the properties of the object it is building.
I don't know Obj-C++, so I don't know if this is possible, but this sounds like a problem for Categories. Expose only the necessary methods to your house in the declaration of the house itself, create a category that contains all the private methods you want to keep hidden.
What about the other way around, using multiple inheritance, so your class is also a Builder? That would mean that the bulk of the algorithms could be in the base class, and be extended to fit the neads of you specific House. It is not very beautiful, but it should let you abstract most of the functionality.