Regarding transient fields - blackberry

I have a class which implements persistable and a transient boolean member in this class. I noticed that thought he variable is declared as transient its state is being persisted. How do i over come this issue. Kindly help. Thanks in advance.

Blackberry's persistence mechanism does not respect transient. Possible solutions are:
split the object into two parts, persistable and not, or
use a different object format (perhaps something generic like a Hashtable) only for persistance, copying out into the "real" object after it is loaded and then writing back into the dummy object for saving.
(See this forum thread)

Related

Make an independent copy of a model instance

I would like one instance of a model in memory to serve as a template for creating other objects for performance reasons, so that duplicates look like the original object but otherwise share no common components with the object they are initialized from, as if they were loaded with Model.find(template_object.id). I've tried some of the available solutions but none seems to do what I need: .dup and .deep_dup will create a new object with nil id and .clone will make some of the fields common to both the initializer and the initialized.
Currently my API is giving out the original objects that I keep as class variables, but I discovered that it leads to obscure memory leaks when the code using the objects manipulates their associations - these are kept in memory indefinitely. I hope that by giving out copies the associations of the template objects will stay untouched and the leak will be gone.
This sounds like the use case for defining a class and just initializing instances. You can customize whatever properties you want shared in the MyClass#new method. Without knowing more about your needs I will add that if you must store a template in memory you could store it as a class variable perhaps MyClass##template but would need to hear more to opine further. 😄
What I found when browsing rails source is the .instantiate method:
MyModel.instantiate(#my_other_instance.attributes_before_type_cast.deep_dup)

Properties in Categories

Why is it allowed to declare properties in categories when neither they nor their accessor methods are synthesized? Is there any performance overhead involved?
Is categorisation purely a compiler technique?
I'm trying to understand how categories work. This just explains what to do and what not to do. Are there any sources which go into more detail?
EDIT : I know that I can use associated references. Thats not what I'm asking for. I want to know why are the properties not synthesised? Is there a performance issue or a security issue if the compiler synthesises them? If there is I want to know what and how?
Why is it allowed to declare properties in categories [...] ?
Properties have many aspects (during compile- and runtime).
They always declare one or two accessor methods on the class.
They can change the selector when the compiler transforms dot notation to messages.
In combination with the #synthesize directive (or by default) they can make the compiler synthesize accessor methods and optionally ivars.
They add introspection information to the class which is available during runtime.
Most of these aspects are still useful when declaring properties in categories (or protocols) and synthesizing is not available.
Is categorisation purely a compiler technique?
No. Categories, as properties, have both compile time as well as runtime aspects.
Categories, for example, can be loaded from dynamic libraries at a later time. So there might already be instances of a class that suddenly gets new methods added. That's one of the reasons categories cannot add ivars, because old objects would be missing these ivars and how should the runtime tell if an object has been created before or after the category has been added.
Before you go into categories, please reconsider the concept of properties in Obj-C: A property is something you can write and read to in an abstract sense, using accessors. Usually, there is an instance variable assigned to it, but there is no need to do so.
A property may also be useful e.g., to set a number of different instance variables in a consistent way, or to read from severals variables or do some calulation.
The crucial fact here: there is no need to have an instance variable assigned to a property.
A category serves as an extensiton of an object's behavior, i.e., to extend its set of methods, without changing the data. If you see a property in it abstract sense, then it add accessors, thus it matches the idea of a category.
But if you synthesize it, an instance variable would be generated what contradicts the idea of a category.
Thus, a property in a category makes only sense if you use it in the uncommon, abstract way, and #synthesize is to ease the common way.
You may want to read NSHipster about how to implement properties storage in categories.
Quoting from the article: "Why is this useful? It allows developers to add custom properties to existing classes in categories, which is an otherwise notable shortcoming for Objective-C."
#synthesize informs the compiler to go ahead and provide a default implementation for the setter and the getter.
Said default setters/getters rely on the existence of some kind of storage inside the object.
Categories do not offer any extra storage, so default setters/getters would have no place to store into, or read from.
An alternative is to use:
#dynamic
and then provide your own implementation and own storage for the said properties.
One way is to use associated objects.
Another would be to store into/read from some completely unrelated place, such as some accessible dictionary of NSUserDefaults or ...
In some cases, for read only properties, you can also reconstruct/compute their values at runtime without any need to store them.

Why are instance variables considered bad practice by Apple?

In Apple's Programming with Objective-C the section on Encapsulating Data states that:
You Can Define Instance Variables without Properties
It’s best practice to use a property on an object any time you need to keep track of a value or another object.
In other words they are strongly recommending that you use private properties rather than instance variables for any private object state.
I am wondering why this might be the case? I understand that properties have features such as KVO, and attributes (strong, weak ...), but in many cases I do not need these features and an instance variable will work just fine.
Are there any good reasons why instance variables might not be considered best practice?
Even though right now your private variable might work as a plain variable, you may decide later that some of properties 'goodies' are useful:
observing
atomic accessors
custom accessors
logging on access
access from subclasses
If you only access your variables as properties, you don't add much overhead (except in tight cycles) and leave room for reaping any of those benefits described above.
Basically, properties are useful even if you don't ever plan on making them public.
Of course, there are places where using an instance variable is still 'more natural', for example if you reimplement Foundation classes in a class cluster (such as NSArray), it's expected that your implementation is private and performant, so I don't use properties then.
Also, I don't think you should read too much into the advice. To me it reads more like "If you've only learned 5 minutes ago about properties and instance variables, let's start with using properties first".
People who are new to the language can go quite far without knowing what the instance variables are.
In other words they are strongly recommending that you use private properties rather than instance variables for any private object state.
Where did you read that they are recommending private properties? I think they mean public variables/properties.
And of course using properties instead of public instance variables has a lots of advantages:
encapsulation and custom getters/setters
memory management
KVO
binary compatibility
and so on
But in my opinion using private properties in general has no advantages and it's much easier to use private instance variables. The only reason I can imagine is to make custom getters/setters for such variables in future, but I don't think that it's a "best practice".
The point is underlaying storage abstraction. So simple yet very powerful.

Grails internals : Auto mapping and Domain object creation

I am trying to make a taglib to represent an object (to read and display at the UI). When creating an object (save method in the controller), I see the domain class and association are created by the auto assignment of parameter
def Book = new Book(params)
It also maps complex types (for eg: joda time). I wonder about the naming convention necessary to facilitate this mapping. Out of curiosity, can someone also point where in the grails source code I could see how grails handles this mapping. I'm still learning Spring and probably this would be a good exercise.
Thanks,
Babu.
AFAIK the naming conventions are rather straightforward. If there's a field params.foo and the object you are binding to has a field foo, it will bind the value, assuming the type conversion works properly. If there's a params.bar.id set with an Long value and your object has a complex property of type Bar, it will lookup this instance and inject it.
If you need more control over the binding process, you might want to use bindData.
If you are interested into the details of the binding process, have a look at Java's PropertyEditor as this is what is being used in the background. I wrote a blog post on how to create and register PropertyEditors a while ago, maybe it helps you getting started with that stuff.

Working with complex objects in Prevayler commands

The demos included in the Prevayler distribution show how to pass in a couple strings (or something simple like that) into a command constructor in order to create or update an object. The problem is that I have an object called MyObject that has a lot of fields. If I had to pass all of them into the CreateMyObject command manually, it would be a pain.
So an alternative I thought of is to pass my business object itself into the command, but to hang onto a clone of it (keeping in mind that I can't store the BO directly in the command). Of course after executing this command, I would need to make sure to dispose of the original copy that I passed in.
public class CreateMyObject implements TransactionWithQuery {
private MyObject object;
public CreateMyObject(MyObject business_obj) {
this.object = (MyObject) business_obj.clone();
}
public Object executeAndQuery(...) throws Exception {
...
}
}
The Prevayler wiki says:
Transactions can't carry direct object references (pointers) to business objects. This has become known as the baptism problem because it's a common beginner pitfall. Direct object references don't work because once a transaction has been serialized to the journal and then deserialized for execution its object references no longer refer to the intended objects - - any objects they may have referred to at first will have been copied by the serialization process! Therefore, a transaction must carry some kind of string or numeric identifiers for any objects it wants to refer to, and it must look up the objects when it is executed.
I think by cloning the passed-in object I will be getting around the "direct object pointer" problem, but I still don't know whether or not this is a good idea...
Cloning doesn't help you with the baptism problem, unless you make sure that the original object has no references to other objects. But that is a different problem than what you described.
If you don't want to write so many createCommands, pass in a Dictionary of name-value pairs and a key to the class to create.
I have never used Prevayler and I'm not sure if I understand your problem, but I think You gave yourself an answer:
Direct object references don't work
because once a transaction has been
serialized to the journal and then
deserialized for execution its object
references no longer refer to the
intended objects - - any objects they
may have referred to at first will
have been copied by the serialization
process
In CreateMyObject keep uniqe identifier of MyObject. Not a reference. Cloning has nothing to do here.

Resources