• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: [Obj-C] if (self) vs. if (self != nil)
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Obj-C] if (self) vs. if (self != nil)


  • Subject: Re: [Obj-C] if (self) vs. if (self != nil)
  • From: Wade Tregaskis <email@hidden>
  • Date: Fri, 24 Feb 2012 09:52:32 -0800

> self = [super init];
> if (self)
> {
> }
> return self;
>
> self = [super init];
> if (self != nil)
> {
> }
> return self;
>
> The Xcode samples promote the first variant, but I'm wondering if the
> second one is more correct?

No.  The more common convention in (Apple's) ObjC is to use implicit boolean values, though an explicit test against nil is fine if that's your preference.

> The "nil" is defined as follows (jumped to definition)
>
> #define nil NULL
> #define NULL ((void*)0)

I'd hazard to say that's an implementation detail.  While you can compare object pointers against NULL, it's strongly against convention - you use nil for pointers to ObjC objects, NULL for other types of pointers.  Hypothetically this protects you from any future changes in how objects are distinguished from "regular" pointers.

> I also heard that generally speaking NULL is not necessarily always
> equal to 0 on all architectures.


That definition is quite archaic.  Though technically speaking it's true, and is thus an argument for actually using NULL rather than 0, it's not the only such argument by far*, and in any case there's enough momentum behind NULL == 0 that this will almost certainly never change.

* = For example, more important arguments are for readability in code, and because 0 is an integer whereas pointers are not.  And that a test against zero is faster than a test against any other specific integer on all modern hardware.
_______________________________________________

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


  • Follow-Ups:
    • Re: [Obj-C] if (self) vs. if (self != nil)
      • From: Scott Ribe <email@hidden>
References: 
 >[Obj-C] if (self) vs. if (self != nil) (From: Oleg Krupnov <email@hidden>)

  • Prev by Date: Re: [Obj-C] if (self) vs. if (self != nil)
  • Next by Date: Re: [Obj-C] if (self) vs. if (self != nil)
  • Previous by thread: Re: [Obj-C] if (self) vs. if (self != nil)
  • Next by thread: Re: [Obj-C] if (self) vs. if (self != nil)
  • Index(es):
    • Date
    • Thread