• 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: objective-c question/clarification
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: objective-c question/clarification


  • Subject: Re: objective-c question/clarification
  • From: Fritz Anderson <email@hidden>
  • Date: Mon, 25 Jun 2001 03:10:11 -0500

This is common practice in C (not just Objective-C). A static variable declared inside a function has local access (attempts to refer to it outside the function will fail), but static lifetime: It is initialized and retains its value just as if it were defined like a static or global variable at the top level of the source file.

In the example below, _sharedInfoWindowController gets initialized to nil when the program is loaded. The initializer is not executed more than once (all statics are initialized only once). On the first call to +[sharedInfoWindowController], the method sees the nil, initializes a controller, and assigns it to _sharedInfoWindowController. That variable retains that value in later calls, so in those later calls, the if (_sharedInfoWindowController) condition fails, and no additional allocation or assignment takes place.

-- F

At 1:40 AM -0400 6/25/2001, email@hidden wrote:
I was working through the rest of ToDo example from the O'Reilly Cocoa and the code snippet below bothered me as there seems to be a hole in my obj-c knowledge. The first line in the code declares a static local variable "InfoWindowController" which it then proceeds to set to nil. The subsequent "if" statement checks to see if the "InfoWindowController" is pointed at anything. Wouldn't "InfoWindowController" always be nil thus allowing for the creation of numerous "info windows" (which I know does not happen). I'm just curious as to the mechanism behind this code, why it works.
From InfoWindowController.m
+ (id)sharedInfoWindowController
{
static InfoWindowController *_sharedInfoWindowController = nil;

if (!_sharedInfoWindowController)
_sharedInfoWindowController = [[InfoWindowController allocWithZ$
[presumably the $ indicates an elision of the rest of the line; don't compile this at home]

return _sharedInfoWindowController;
}


References: 
 >objective-c question/clarification (From: email@hidden)

  • Prev by Date: Re: NSScanner searches from start
  • Next by Date: Re: Confusion
  • Previous by thread: objective-c question/clarification
  • Next by thread: Re: objective-c question/clarification
  • Index(es):
    • Date
    • Thread