This would make an excellent recruitment-test for an Objective-C programmer.
Both of these snippets are from the Apple developer example code collection. One of them is correct, and the other will likely make your application burst into flames*.
Code snippet 1:
- (void)setArguments:(NSDictionary *)arguments
{
[arguments copy];
[_arguments release];
_arguments = arguments;
}
Code snippet 2:
- (void)setURLToLoad:(NSURL *)URL
{
[URL retain];
[URLToLoad release];
URLToLoad = URL;
}
Quiz questions (select text for answer):
Q: Which one is broken? (1p)
A: Snippet 1. It throws away the copy, and instead assigns a non-retained variable.
Q: Why is the other one not broken? (2p)
A: Because retain modifies the object, so assigning the retained object is fine.
Q: Why is the author using copy instead of retain? (5p)
A: Because the object could be a NSMutableDictionary which could unexpectedly change later.
Q: How should they both be written instead so that this will never happen? (20p)
A: Like ‘[_v release];_v = [v retain]’ or ‘[_v release];_v = [v copy]’
Thanks Apple, made my day here (hey, it’s raining).
*) The computer supplies ‘BusError’ and you’ll have to provide the pyrotechnics. I usually go with illustrative hand-waving and onomatopoetic sound effects.