Objective-C (iOS) variable replacement in array values - ios

How do I write NSArray values to utilize a variable similar to this NSString:
Levelname=[NSString stringWithFormat:#"Background1Level%d.png",LevelNO];
[backgroundimagview setImage:[UIImage imageNamed:Levelname]];
Here is the code block I need to convert to use the LevelNO variable:
[character setImage:[UIImage imageNamed:#"character1_09.png"]];
character.animationImages=[NSArray arrayWithObjects:
[UIImage imageNamed:#"character1_01.png"],
[UIImage imageNamed:#"character1_02.png"],
[UIImage imageNamed:#"character1_03.png"],
[UIImage imageNamed:#"character1_04.png"],nil ];

loop through them with an integer and instead of "LevelNO" use that integer. Something like this:
for(int i = 0; i < {number of levels here}, i++)
{
Levelname=[NSString stringWithFormat:#"Background1Level%d.png",i];
[myArray addObject:[UIImage imageWithName:Levelname];
}
Make sure to keep an array and replace myArray

Related

how to display the value stored in array by using for loop in objective-c

LOGIC:
5 image in a array
example:
apple.png,mango.png,bird.png,sun.png,moon.png
I need to use arc4random in this array, so I got index as 1, so value got mango.png
in other array I stored
number = [[NSMutableArray alloc]initWithObjects:#"4",#"2",#"9",#"1",#"8",#"7",#"5",#"3",#"6",#"10", nil];
and used arc4random and i got the output as index:2 value as:9
then i need to print 9 times image of mango in image view.
please help how to code this using objective-c
As per my understanding, you have to show random Image in ImageView on the basis of random number.
Have a look below code,
images = [[NSMutableArray alloc]initWithObjects:[UIImage imageNamed:#"Navarre-Family-Eye-Care-Navarre-Florida-Optometrist-Santa-Christmas-Toy-Safety.jpg"],[UIImage imageNamed:#"Christmas-Wallpapers-HD-Picture.jpg"],[UIImage imageNamed:#"Christmas-Wallpaper-jesus-9413550-1024-768.jpg"],[UIImage imageNamed:#"tree.jpg"],[UIImage imageNamed:#"luxury-christmas-napkins-father-christmas-1635-p.jpg"],[UIImage imageNamed:#"Navarre-Family-Eye-Care-Navarre-Florida-Optometrist-Santa-Christmas-Toy-Safety.jpg"],[UIImage imageNamed:#"Christmas-Wallpapers-HD-Picture.jpg"],[UIImage imageNamed:#"Christmas-Wallpaper-jesus-9413550-1024-768.jpg"],[UIImage imageNamed:#"tree.jpg"],[UIImage imageNamed:#"luxury-christmas-napkins-father-christmas-1635-p.jpg"], nil];
int randomIndex=arc4random() % images.count;
UIImage *selectedImage = [images objectAtIndex:randomIndex]; //random selected image
number = [[NSMutableArray alloc]initWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10", nil];
int randomNumber = arc4random() % number.count; //random selected number
NSInteger indexValue = [number indexOfObject:[NSString stringWithFormat:#"%d",randomNumber]]; // get index number of your random number
for (int i = 0; i <indexValue ; i++) {
NSLog(#"%#", selectedImage);
yourImageView.Image = selectedImage;
}
you have to show number of times images in NSLog as per the random number comes. so just add the following code at the end of your existing code.
int count = [[number objectAtIndex:ran] intValue];
for(int i=0; i<count; i++)
{
NSLog(#"%#",v);
}
Important thing is where do you want to display the image.
From the above snippet what I can understand is v(NSArray) is assigned with UIImage.
If you want to use v as NSArray then add UIImage as an object to the Array, then you will be able to access image using index.
NSArray *v=[[NSArray alloc] initWithObjects:[imagesArray objectAtIndex:randomIndex], nil];
then you can NSLog the image object with below code
for (int i= 0 ; i<ran; i++) {
NSLog(#"%#",[v objectAtIndex:0]);
_cardsImageView.image = [v objectAtIndex:0]
}

How to access Object of Key in NSDictionary with NSNumber instead of NSString in Objective-C

I have a NSDictionary and Int Variable :
mainDic = #{#1:#"1.jpg",#2:#"2.jpg"};
indexpath.row = 2;
I want to access to object for value 2 using indexpath.row like this :
cell.pic.image = [UIImage imageNamed:mainDic[indexpath.row]];
But it doesn't work. ...
mainDic = #{#1:#"1.jpg",#2:#"2.jpg"}; uses NSNumbers for keys in this dictionary.
#1 creates a NSNumber, its just a shortcut for [NSNumber numberWithInt:1].
so your Dictionary looks like this: NSDictionary <NSNumber *, NSString *> *mainDic;.
The row property of NSIndexPath is a readonly integer.
You try to access your NSDictionary with an integer and not with NSNumber as key, the right call should be:
NSNumber *row = [NSNumber numberWithInteger:indexpath.row];
cell.pic.image = [UIImage imageNamed:mainDic[row]];
But I would just use an array, its way simpler to access the images from it.
NSArray *images = #[#"1.jpg",
#"2.jpg",
#"3.jpg"];
cell.pic.image = [UIImage imageNamed:images[indexpath.row]];
Your key should be in the left side, not in right. And also there is typo, I think: #"2,jpg". But should be #"2.jpg".
But in general use an array instead of NSDictionary for this. Because Integer can't be a key, as I remember.
Check your input dictionary. You could entered wrong image name. Replace it with:
mainDic = #{#"1" : #"1.jpg", #"2" :#"2.jpg"};
cell.pic.image = [UIImage imageNamed:[mainDic valueForKey:[NSString stringWithFormat:#"%#", indexpath.row]]];

Using an NSMutableArray to set images to multiple UIImageViews

I'm totally new to iOS development so forgive me if this question is stupid, but its wrecking my head.
I've set myself the task of building a Hangman Game for iPhone. When the game starts I want the letters of the alphabet to randomly populate into 26 UIImageView's that I have already setup in my ViewController.
I have 2 NSMutableArray's setup. One holds the UIImage reference for the Alphabet images and the other is an array of strings containing the names of all the UIImageViews.
What I'm looking to do is run through a for or a while loop and have the images assigned to the UIImageViews.
Here is the code I'm currently using.
- (void)randomizeAlphabet
{
// Code to randomise Letters on start up of the App.
NSMutableArray *alphabet = [[NSMutableArray alloc] initWithObjects:
[UIImage imageNamed:#"A.png"],
[UIImage imageNamed:#"B.png"],
[UIImage imageNamed:#"C.png"],
[UIImage imageNamed:#"D.png"],
[UIImage imageNamed:#"E.png"],
[UIImage imageNamed:#"F.png"],
[UIImage imageNamed:#"G.png"],
[UIImage imageNamed:#"H.png"],
[UIImage imageNamed:#"I.png"],
[UIImage imageNamed:#"J.png"],
[UIImage imageNamed:#"K.png"],
[UIImage imageNamed:#"L.png"],
[UIImage imageNamed:#"M.png"],
[UIImage imageNamed:#"N.png"],
[UIImage imageNamed:#"O.png"],
[UIImage imageNamed:#"P.png"],
[UIImage imageNamed:#"Q.png"],
[UIImage imageNamed:#"R.png"],
[UIImage imageNamed:#"S.png"],
[UIImage imageNamed:#"T.png"],
[UIImage imageNamed:#"U.png"],
[UIImage imageNamed:#"V.png"],
[UIImage imageNamed:#"W.png"],
[UIImage imageNamed:#"X.png"],
[UIImage imageNamed:#"Y.png"],
[UIImage imageNamed:#"Z.png"],
nil];
NSMutableArray *imgViewsAlphabet = [[NSMutableArray alloc] initWithObjects:
#"letterA",
#"letterB",
#"letterC",
#"letterD",
#"letterE",
#"letterF",
#"letterG",
#"letterH",
#"letterI",
#"letterJ",
#"letterK",
#"letterL",
#"letterM",
#"letterN",
#"letterO",
#"letterP",
#"letterQ",
#"letterR",
#"letterS",
#"letterT",
#"letterU",
#"letterV",
#"letterW",
#"letterX",
#"letterY",
#"letterZ"
, nil];
//Randomly assign the letter from the array
while ([alphabet count] > 0 )
{
int index = arc4random_uniform([alphabet count]);
[(UIImageView *)[imgViewsAlphabet objectAtIndex:index] setImage:[alphabet objectAtIndex:index]];
[alphabet removeObjectAtIndex:index];
[imgViewsAlphabet removeObjectAtIndex:index];
}
}
The code above seems fine in Xcode but when it compiles it crashes out.
Any help at all would be greatly appreciated.
Cheers,
TQ
You have 2 arrays, imgViewsAlphabet and alphabet
imgViewsAlphabet is an array of strings.
alphabet is an array of UIImage objects.
This line:
[(UIImageView *)[imgViewsAlphabet objectAtIndex:index]
setImage:[alphabet objectAtIndex:index]];
Is attempting to fetch an object from the imgViewsAlphabet array, and send it a setImage: message.
What kinds of object are in your imgViewsAlphabet array? Do those kind of objects understand the setImage method?
#DuncanC is right. It seems like you're looking to have an array of image views with images chosen in a random, non-repeating way. A good simple approach is to build that array sequentially, then shuffle it:
NSMutableArray *imageViewArray = [NSMutableArray array];
for (char aChar = 'A'; aChar <= 'z'; ++aChar) {
NSString *imageName = [NSString stringWithFormat:#"%c.png", aChar];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageViewArray addObject:imageView];
}
Now shuffle it. There are many ways to do this, like the Fisher-Yates algorithm. Here's a high voted SO answer that does it. In a nutshell:
NSUInteger count = [imageViewArray count];
for (NSUInteger i = 0; i < count; ++i) {
NSInteger remainingCount = count - i;
NSInteger exchangeIndex = i + arc4random_uniform(remainingCount);
[imageViewArray exchangeObjectAtIndex:i withObjectAtIndex:exchangeIndex];
}
This will leave you with an array of UIImageViews whose images are named #"A.png", #"B.png", etc. in randomized order. You'll need to assign these frames and add them as subviews to some view in order to be seen.

loop to set UIImages from document directory on viewDidLoad

I have 9 buttons whose images are set by the user dynamically. Each button's current image is saved the user documents folder. In viewDidLoad id like to re-set each image to it's UIButton.
I can do this easily enough with:
NSString *filePath = [self documentsPathForFileName: #"boss1.png"];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[boss1Button setImage:savedBoss forState:UIControlStateNormal];
...... 8 more times....
Of course Id prefer to do it using a loop. Only, Im not sure what that would look like in objective C. In jQuery I could do something like:
$('.bosses').each(function( index ) {
var imageUrl='../images/boss'+(index+1)
$('#'+this.id).css('background-image', 'url(' + imageUrl + ')')
});
How can I create a similar objective-C loop that would increment the boss image name and button name similarly?
Furthermore, is there a better way to do this entirely?
I feel like maybe having an NSArray of image urls and an NSArray of UIButton names and pairing them together using a loop might be better.... but again I'm not sure what the syntax would look like for that here.
Try like this and have button tag like 1 to 8
for (id subview in self.view.subviews) {
if([subview isKindOfClass:[UIButton class]]) {
UIButton* button = (UIButton*)subview;
NSString *filePath = [self documentsPathForFileName:[NSString stringWithFromate#"boss%d.png", button.tag]];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[button setImage:savedBoss forState:UIControlStateNormal];
}
}
This will do.
it will be like:
//Add all the buttons in an array for easy loop
NSArray *array = #[btn1,btn2,btn3,btn4... etc];
NSString *name = #"BOSS";
int x = 1;
for(UIButton *btn in array){ // loop through all the buttons
NSString *filePath = [self documentsPathForFileName:[NSString stringWithFormat:#"%#%d.png",name,x]];
NSData *pngData = [NSData dataWithContentsOfFile:filePath];
UIImage *savedBoss = [UIImage imageWithData:pngData];
[btn setImage:savedBoss forState:UIControlStateNormal];
x++;
}

getting value from the loop to store in array

I have this code from which i am checking songs that are present in my app and storing the number of songs in an NSMUTABLEArray but there is something wrong it always shows null
for (int i = 1; i < 100; ++i) {
// Load the plist
NSString *plist = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"%d",i] ofType:#"mp3"];
if (nil == plist) {
NSLog(#"not found (%i)", i);
continue;
}
NSLog(#"Found Songs (%i)",i);
[MYNSMUTABLEArray addObject:[NSNumber numberWithInt:i]];
NSLog(#"%#",MYNSMUTABLEArray);
}
the i variable is working absolutely fine
You need to create your mutable array, so that an object exists to store the data. I presume that the code at the moment is sending the addObject: message to nil.
I'd strongly suggest a better variable name than MYNSMUTABLEArray, so here is my code snippit that should go before the loop.
NSMutableArray* myMutableArray = [NSMutableArray alloc] init];
Then where you are adding the object, you'd use:
[myMutableArray addObject:#(i)];
Bootnote: A little tip, you can use # literals to automatically box your primitive int value into an NSNumber object. This is used in the addObject: example, and is in the form #(int).

Resources