How to Use the Singleton Pattern in iOS App Development - dummies

How to Use the Singleton Pattern in iOS App Development

By Rajiv Ramnath

Design patterns are formal ways of documenting solutions to design problems; one of the most common patterns used in the Symbol class is the Singleton Pattern. This pattern is used in iOS app development and is presented below in the Tic-Tac-Toe application.

The Singleton pattern is used in the Symbol class, notice the customized format of this pattern in the Tic-Tac-Toe application:

  • Rather than the one instance returned by the textbook Singleton pattern, three instances (one each for the X, O, and blank symbols) are allowed in the Symbol class. These instances are managed by the three static, or class, methods. One of these methods is shown here:

    +(TTTSymbol*) SymbolXCreate{
     @synchronized([TTTSymbol class]){
      if (SymbolX == nil){
       SymbolX = [[TTTSymbol alloc] init];
       SymbolX->value = MARKX;
      }
      return SymbolX;
     }
    }
  • The technique used in the Singleton pattern to create only one instance is used in the method getBitmapForSymbol to get the images for the X, O, and blank symbols:

    - (UIImage *) getBitmapForSymbol{
      @synchronized([TTTSymbol class]){
       if (!bitMapsInitialized){
        NSString* imagePath =
         [[NSBundle mainBundle]
          pathForResource:
           @"Images.bundle/x" ofType:@"png"];
        imageX = [[UIImage alloc]
         initWithContentsOfFile:imagePath];
        imagePath =
         [[NSBundle mainBundle]
          pathForResource:
           @"Images.bundle/o" ofType:@"png"];
        imageO =
         [[UIImage alloc] initWithContentsOfFile:imagePath];
        imagePath =
         [[NSBundle mainBundle]
          pathForResource:
           @"Images.bundle/blank" ofType:@"png"];
        imageBlank =
         [[UIImage alloc] initWithContentsOfFile:imagePath];
        bitMapsInitialized=true;
       }
      }
      UIImage *imageSelected = imageBlank;
      if (self == [TTTSymbol SymbolXCreate]) imageSelected = imageX;
      else if (self == [TTTSymbol SymbolOCreate])
       imageSelected = imageO;
      return imageSelected;
     }
  • Because iOS apps can be multithreaded, Singleton is modified to deal with multiple threads by using the @synchronized annotation.