UIImageView
iOS Development
Swift
Image Handling
Programming Tips

UIImageView - How to get the file name of the image assigned?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

A common question iOS developers ask is how to retrieve the filename of the image currently displayed in a UIImageView. The short answer is that you cannot, because UIImage does not store the name of the file it was created from. Understanding why Apple designed it this way helps you pick the right workaround for your specific use case.

Why UIImage Does Not Expose the Filename

When you call UIImage(named: "photo.png"), the system loads the image data, decodes it, and caches the result. Once that process is complete, the UIImage object holds pixel data and display metadata such as scale and orientation. It does not retain the original filename or asset catalog name. Apple made this choice for several reasons. Images can come from network downloads, camera captures, or in-memory drawing contexts, none of which have a meaningful filename. Storing the name would add memory overhead for a property most code paths never need. The framework treats all images uniformly regardless of origin, which simplifies the internal caching and rendering pipeline.

Because of this design, you need to track the filename yourself if your app logic requires it.

Using accessibilityIdentifier

The simplest workaround is to store the image name in the accessibilityIdentifier property of the UIImageView. This property is a plain String? that is already available on every UIView:

swift
1let imageView = UIImageView()
2let imageName = "profile_photo"
3
4imageView.image = UIImage(named: imageName)
5imageView.accessibilityIdentifier = imageName
6
7// Later, retrieve the name
8if let name = imageView.accessibilityIdentifier {
9    print("Current image: \(name)")
10}

This approach is quick and requires no extra code. The downside is that accessibilityIdentifier is meant for UI testing and accessibility, so using it for business logic can create confusion if your team also relies on it for test automation.

Using Associated Objects

Objective-C runtime associated objects let you attach arbitrary data to any object instance without subclassing. In Swift, you can use this to add an imageName property to UIImageView through an extension:

swift
1import ObjectiveC
2
3private var imageNameKey: UInt8 = 0
4
5extension UIImageView {
6    var imageName: String? {
7        get {
8            return objc_getAssociatedObject(self, &imageNameKey) as? String
9        }
10        set {
11            objc_setAssociatedObject(
12                self,
13                &imageNameKey,
14                newValue,
15                .OBJC_ASSOCIATION_RETAIN_NONATOMIC
16            )
17        }
18    }
19}

Now you can set and retrieve the name on any UIImageView without subclassing:

swift
1let imageView = UIImageView()
2imageView.image = UIImage(named: "banner")
3imageView.imageName = "banner"
4
5// Later
6print(imageView.imageName ?? "No name set")

The .OBJC_ASSOCIATION_RETAIN_NONATOMIC policy keeps a strong reference to the string and avoids the overhead of atomic access. Memory is released automatically when the UIImageView is deallocated.

Subclassing UIImageView

If you want a cleaner API and are comfortable with subclassing, you can create a custom UIImageView that wraps the image-setting logic:

swift
1class NamedImageView: UIImageView {
2    private(set) var imageName: String?
3
4    func setImage(named name: String) {
5        self.image = UIImage(named: name)
6        self.imageName = name
7    }
8
9    func setImage(_ image: UIImage?, name: String?) {
10        self.image = image
11        self.imageName = name
12    }
13}

Usage is straightforward:

swift
1let imageView = NamedImageView()
2imageView.setImage(named: "avatar")
3
4if let name = imageView.imageName {
5    print("Displaying: \(name)")
6}

This approach makes the relationship between the image and its name explicit in the type system. The tradeoff is that you must use NamedImageView everywhere you need this feature, which may not be practical if you are working with storyboards or third-party libraries that create UIImageView instances for you.

Tracking Names with a Dictionary

When you need to track image names across many image views without modifying any classes, a simple dictionary works well:

swift
1class ImageNameTracker {
2    static let shared = ImageNameTracker()
3    private var names: [ObjectIdentifier: String] = [:]
4
5    func set(name: String, for imageView: UIImageView) {
6        let key = ObjectIdentifier(imageView)
7        names[key] = name
8    }
9
10    func name(for imageView: UIImageView) -> String? {
11        let key = ObjectIdentifier(imageView)
12        return names[key]
13    }
14
15    func remove(for imageView: UIImageView) {
16        let key = ObjectIdentifier(imageView)
17        names.removeValue(forKey: key)
18    }
19}
swift
1let imageView = UIImageView()
2imageView.image = UIImage(named: "hero_banner")
3ImageNameTracker.shared.set(name: "hero_banner", for: imageView)
4
5// Retrieve later
6let name = ImageNameTracker.shared.name(for: imageView)

Be mindful that this tracker holds a reference to the ObjectIdentifier (not the image view itself), so it will not prevent deallocation. However, you should call remove(for:) when an image view is no longer needed to avoid stale entries accumulating in the dictionary.

Using a Property Wrapper (Swift 5.1+)

For a more modern Swift approach, you can wrap the associated-object pattern in a property wrapper:

swift
1@propertyWrapper
2struct AssociatedString {
3    private var key = UUID()
4
5    var wrappedValue: String? {
6        get { nil }  // default until set on an instance
7        set { }
8    }
9
10    static subscript<T: AnyObject>(
11        _enclosingInstance instance: T,
12        wrapped wrappedKeyPath: ReferenceWritableKeyPath<T, String?>,
13        storage storageKeyPath: ReferenceWritableKeyPath<T, AssociatedString>
14    ) -> String? {
15        get {
16            let wrapper = instance[keyPath: storageKeyPath]
17            return objc_getAssociatedObject(instance, &instance[keyPath: storageKeyPath].key) as? String
18        }
19        set {
20            objc_setAssociatedObject(
21                instance,
22                &instance[keyPath: storageKeyPath].key,
23                newValue,
24                .OBJC_ASSOCIATION_RETAIN_NONATOMIC
25            )
26        }
27    }
28}

This is more advanced and is mainly useful in larger codebases where you want a reusable pattern for attaching metadata to UIKit objects.

Common Pitfalls

  • Assuming UIImage(named:) stores the filename somewhere accessible. It does not.
  • Forgetting to update the stored name when you change the image, leading to stale values.
  • Using accessibilityIdentifier for image names while also relying on it for UI testing, causing test selectors to break.
  • Not cleaning up dictionary entries when image views are deallocated, which leads to memory waste over time.
  • Storing filenames with or without extensions inconsistently, making lookups fail.

Summary

  • UIImage deliberately does not retain the filename or asset name used to create it.
  • The simplest workaround is storing the name in accessibilityIdentifier, but it conflicts with accessibility and testing uses.
  • Associated objects via objc_setAssociatedObject let you add a custom imageName property through an extension without subclassing.
  • Subclassing UIImageView gives you a type-safe API but limits flexibility with storyboards and third-party code.
  • A shared dictionary tracker works when you need to track names across many image views without modifying any classes.
  • Whichever approach you choose, always update the stored name whenever you change the image to keep them in sync.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.