7

as question says, How does imageNamed work when there are multiple files with the given name under the resource directory?

Is there a way to differentiate two different files with same name (but different path)?

Thank you

eugene
  • 39,839
  • 68
  • 255
  • 489

1 Answers1

8

The folders in any Xcode bundle are "groups". That is, they are not actual directories. The files in those groups are still located in the bundle's root.

So, having two (or more) files with the same name in the app bundle is impossible.

See: http://majicjungle.com/blog/?p=123

The problem with Groups:

The directory structure is lost when it’s copied to the iphone app, and so inside your app bundle is just a big list of all your resources in the base directory. As a result of this, duplicate filenames become an issue. If any files within your directory structure on disk contain the same filename, the build process silently screws everything up. It appears to be ‘first in wins’, with only one of the resources making it into the app bundle. So it’s no good if you have a bunch of different level packages each containing a different ‘Terrain.png’ file.

If you maintain your directory structure by creating folder references, this eliminates the problem of duplicate file names. However, retrieving the files is the problem.

What you can do is use the NSBundle class:

[[[NSBundle mainBundle]resourcePath]stringByAppendingPathComponent:@"path/to/file.jpg"]
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
  • ah, when I add files to the project I can add them using "recursively create groups for any added folders", and "create folder references for any added folders". If I use the second option, I may be able to have two files with the same name. Wonder If I can use "imageNamed" on files which were added that way – eugene Jan 03 '11 at 02:28
  • NSBundle method would cache the image as imageNamed? – eugene Jan 03 '11 at 03:16
  • The sample above retrieves the path for the file. That should be used as the parameter for the UIImage imageNamed method. – Evan Mulawski Jan 03 '11 at 03:41
  • having tried imageNamed and failed, looks like I need to use imageWithContentsOfFile with the path returned. – eugene Jan 03 '11 at 04:26
  • Ah, yes. That's what I get for trying to remember the documentation off the top of my head. Glad you got it working. – Evan Mulawski Jan 03 '11 at 14:03
  • You could alternatively create additional bundles with different resource sets and include these in your main bundle. – Andy J Buchanan Jan 03 '11 at 20:25