PDA

View Full Version : Puzzling Obj C Question/Error




DaveP
Nov 14, 2005, 05:37 PM
Hey Guys,
(a bit of background in case you are interested) I am a reasonably proficient programmer, but have only been using XCode and Obj C for the past half a year of so to create a tool for my Master's degree thesis.

Anyways, on a few occasions I have had cases where nested message passes/function calls do not work (either compile or run-time errors), but when I break things up it works. Usually nesting is no problem, but occasionally it happens. I usually assume I am just doing something wrong that I can't figure out. Here is an example: (basically, transition is an instance of an object with a variableResets member array which I want to add an object, variableReset)

(broken up)
NSMutableArray* arr = [transition variableResets];
[arr addObject:variableReset];
[transition setVariableResets:arr];

(one line)
[transition setVariableResets:[[transition variableResets] addObject:variableReset]];

The one line version gives me a compile error of "invalid use of void function." Both setVariableResets and addObject are void functions, but I can't see how either are being used incorrectly. And variableResets does return a mutable array, but I am guessing that it somehow has to do with something like that.

It's probably some sort of simple thing that I am just overlooking or unaware of, but maybe someone knows what the error is. And I'll stress that I really don't care about having to break it up, but it really puzzles me as to why?



HexMonkey
Nov 14, 2005, 05:51 PM
[[transition variableResets] addObject:variableReset]

does not return anything, so when you use the code:

[transition setVariableResets:[[transition variableResets] addObject:variableReset]];

there is an error because you are using a non-existent value as a parameter. Breaking it up, your code is equivalent to:

id returnValue = [[transition variableResets] addObject:variableReset]; //Error, as there is no return value
[transition setVariableResets:returnValue];

Here it is a bit more clear what the problem is.

As a sidenote, you shouldn't need to call -setVariableResets anyway. When you send the variableResets message to transition, you are returned a pointer to the array it uses, not a copy. Therefore, when you change the array, the array transition uses is also changed. The following code should do what you want:

[[transition variableResets] addObject:variableReset];

DaveP
Nov 14, 2005, 05:57 PM
Yep, that would do it. I knew it had to be something dumb. Thank you very much. And you are correct, I am miss-using pointers.

(That's one thing that is annoying about Cocoa/Obj C. Not many/any people I know use it so I can't just turn to a friend and do the "hey, I'm an idiot. why doesn't this work" about once a week. Oh well.)