I cannot possibly imagine how yielding the string image5image4image3image2image1.jpg
in string3
in your “answer” to your own question could be construed as useful or a solution (I pasted your code into an Xcode Foundation tool project w/NUMIMAGES set to 5).
It seems that Objective C jumps thru hoops to make seemingly simple tasks extremely difficult.
Read the Objective-C Guide and the String Programming Guide, then make draw your conclusions. Criticizing something you don’t understand is generally counter-productive (we’ve all done it, though — easy to do when frustrated).
I simply need to create a sequence of strings, image1.jpg, image2.jpg, etc etc
Naive solution:
#define NUMIMAGES 5
NSMutableArray *fileNames = [NSMutableArray array];
for(int i = 0; i<5; i++)
[fileNames addObject: [NSString stringWithFormat: @"image%d.jpg", i]];
NSLog(@"fileNames %@", fileNames);
Outputs:
fileNames (
"image0.jpg",
"image1.jpg",
"image2.jpg",
"image3.jpg",
"image4.jpg"
)
Note that there isn’t anything particularly wrong with the naive solution. It is just more fragile, less efficient, and more code than is necessary.
One Possible Better Solution
-
Add all images into your application project as resources.
-
Use the NSBundle API to grab URLs to all images at once.
I.e.:
NSArray *paths = [[NSBundle mainBundle] pathsForResourcesOfType: @"jpg" inDirectory: nil];
Not only does this remove hardcoding of image names from your code, it also allows the system to optimize directory enumeration and path generation. If you want to load only a subset of images — say you are writing a game and have a series of images related to monsters — then put all the related images in a single directory, add the directory to your Resources, then pass that directory’s name as the second argument to the above method.
All of this — and much more — is documented in the resource programming guide.
2
solved Generating a list of Strings in Obj C [closed]