Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between UIImage(named:) and UIImage(imageLiteralResourceName:)?

Swift 3/iOS 10 added a new initializer on UIImage, imageLiteralResourceName:

extension UIImage {

    required public convenience init(imageLiteralResourceName name: String)
}

How does this differ from public init?(named name: String)? I named is a failable initializer while imageLiteralResourceName will crash on an invalid image name. Does imageLiteralResourceName trade safety for performance? When should you use imageLiteralResourceName over named?

like image 486
JAL Avatar asked Jun 14 '16 02:06

JAL


People also ask

What is the difference between UIImage and UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage . Save this answer.

What is UIImage?

An object that manages image data in your app.

How do I add an image to UIImage?

With Interface Builder it's pretty easy to add and configure a UIImageView. The first step is to drag the UIImageView onto your view. Then open the UIImageView properties pane and select the image asset (assuming you have some images in your project).

How do I display an image in Objective C?

UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 20.0, 0.0, 0.0)]; UIImage *myimg = [UIImage imageNamed:@"A1. jpg"]; imageview. image=myimg; [imageview sizeToFit]; And don't forget to add image view to view hierarchy.


1 Answers

Looking at the open-source implementation of UIKit, there seems to be no difference:

extension UIImage : _ImageLiteralConvertible {
  private convenience init!(failableImageLiteral name: String) {
    self.init(named: name)
  }

  public required convenience init(imageLiteralResourceName name: String) {
    self.init(failableImageLiteral: name)
  }
}

public typealias _ImageLiteralType = UIImage

All it does is force-unwrap the result of init(named:).

It seems like it's just an implementation of the _ImageLiteralConvertible protocol found in CompilerProtocols.swift :

public protocol _ImageLiteralConvertible {
  init(imageLiteralResourceName path: String)
}

AppKit also has a similar implementation:

extension NSImage : _ImageLiteralConvertible {
  private convenience init!(failableImageLiteral name: String) {
    self.init(named: name)
  }

  public required convenience init(imageLiteralResourceName name: String) {
    self.init(failableImageLiteral: name)
  }
}

public typealias _ImageLiteralType = NSImage

This might have to do with the new image literal functionality (#imageLiteral) added to Xcode 8 and should never be called directly.

like image 55
JAL Avatar answered Sep 27 '22 23:09

JAL