So I’m trying to write an Objective-C macro that takes an object and a value, releases the original contents, and makes the assignment. Ideally, it would look like this:
myObj = RELEASE_AND_ASSIGN([SomeObject object])
Some things to note, if we leave out the assignment and put the object in the macro, the macro is easily written like so:
#define RELEASE_AND_ASSIGN_TO(obj, expr) [obj release]; obj = expr;
The reason why I don’t want it that way is I feel that reading the code is tougher. I want my eyes to see the assignment on the left. Having something akin to a function call in the place of an assignment I think is awful for clean code and readability.
I tried one hybrid possibility:
#define RELEASE_AND_ASSIGN_TO(obj, expr) [obj release], obj = expr;
The idea is that the release and assignment occurs, and the comma operator returns obj. Much to my confusion, it seems that Objective-C wants to use the [obj release]’s return value. I don’t know why, I thought the right side was taken?
I’m a little lost. Right now, not having the assignment made explicit when calling the macro I don’t think is a style I want to advocate. Any advice?
I don’t know what the heck you are trying to do, but the comma operator takes the right expression, yes, but then you must also put
(and)around it, for else the statementwill just be
but
will be
So try it like this: