Re: Good idea/bad idea?
Re: Good idea/bad idea?
- Subject: Re: Good idea/bad idea?
- From: Andy Lee <email@hidden>
- Date: Thu, 24 Apr 2014 11:23:52 -0400
On Apr 24, 2014, at 10:33 AM, Alex Zavatone <email@hidden> wrote:
> I was just asked yesterday if there is any shorthand in Objective-C for "if this thing = nil, then instantiate a new instance from the class"
>
> Something like this:
>
> NSString x;
>
> if ([x isEqualtoString:nil]) {
> x = @"yo";
> }
I know this is just for illustrative purposes, but this won't work because messages to nil return zero, and so the if-test will always return false. You want:
NSString *x; // Added missing "*" :).
if (x == nil) {
x = @"yo";
}
> And we messed around a bit looking for any shorthand and though it looked like a terrible idea since the comparison is done against integers using the ternary operator, I'd like to know exactly why it's a terrible idea.
>
> NSString x;
>
> x = (x) ?: @"yo";
That's how I'd do it. It's equivalent to
x = x ? x : @"yo"; // Note you don't need the parens.
which in turn is equivalent to the if statement above. It's perfectly okay to test a pointer for nil in this way:
<http://c-faq.com/null/ptrtest.html>
We do it all the time, as in
self = [super init];
if (self) {
...
}
--Andy
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden