I want to do this:
[[ClassA new] addObject:[[ClassA new] addObject:[ClassA new]]];
but the compiler returns:
"error: invalid use of void expression"
Is there a way to do it? like in java:
ClassA = new ClassA( new ClassA( new ClassA()));
The real problem is that -[ClassA addObject:] very likely has a return type of void, so you can't nest that expression as the argument to the outer -addObject: call. For an example, see the documentation for -[NSMutableArray addObject:] — the method signature is - (void) addObject:(id)anObject. This can catch you off guard if you are used to different behavior in another language, particularly Java. Also note that -removeObject: returns void, not the object that was removed.
In addition, everyone is missing the point that +new is inherited unless overridden — see +[NSObject new]. However, using +new is "out of vogue", and +alloc/-init... is preferred. One reason is that since +new calls to -init anyway, you must create a +new... variant to match each -init... in the class. By that point, you get a lot of unnecessary code to solve a non-problem. I personally only use +new very rarely, and only when I know I'm only using -init.
Since you're coming from a Java background, check out this SO question if you're curious about why Objective-C uses alloc/init instead of new like Java, C++, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With