Okay, so i'm trying to give 7 different labels names using an array and a for loop.
Code:
id huller[] = {hul18.text, hul17.text, hul16.text, hul15.text, hul14.text, hul13.text, hul12.text, hul11.text, hul10.text, hul9.text, hul8.text, hul7.text, hul6.text, hul5.text, hul4.text, hul3.text, hul2.text, hul1.text};
for (int i = 0; 7 > i; i++) {
huller[i] = [NSString stringWithFormat:#"%i", x + 1];
NSLog(#"%#", huller[i]);
}
The name change in the NSLog, but they do not change in the simulator. What is wrong?
Assuming hul18, hul17, etc. are all UILabel objects, then do this:
NSArray *labels = [ hul18, hul17, hul16, hul15, hul14, hul13, hul12, hul11, hul10, hul9, hul8, hul7, hul6, hul5, hul4, hul3, hul2, hul1 ];
// Change the text of every label in the array
for (int i = 0; i < labels.count; i++) {
UILabel *label = labels[i];
label.text = [NSString stringWithFormat:#"%i", x + 1]; // Do you really want 'x' here or 'i'?
NSLog(#"%#", label.text);
}
If you want the text to change too, then you have to set the text manually.
NSArray *labels = //Array of labels;
for (int i = 0; 7 > i; i++) {
huller[i] = [NSString stringWithFormat:#"%i", x + 1];
labels[i].text = huller[i];
NSLog(#"%#", huller[i]);
}
Related
I have an array of NSDictionary.NSDictionary has a key named as multiple_image key that contain string separated by ,.
I want set of array that contain 123.png for multiple_images key.
Can some one show me how to do this using NSPredicate or without predicate.
//Array
{
Image = "<UIImage: 0xf72df30>";
active = yes;
"admin_id" = 169;
"category_id" = 32;
"chef_id" = 175;
descr = "Cool tea to cool down the mind.";
id = 110;
"multiple_images" = "Jellyfish.jpg,345.png";
name = "Southern Sweet Ice Tea";
price = 160;
rating = 3;
selected = 0;
"subcat_id" = 23;
"tag_id" = 45;
"tax_id" = 10;
"tax_value" = "12.00";
},
{
Image = "<UIImage: 0xf72ebd0>";
active = yes;
"admin_id" = 169;
"category_id" = 31;
"chef_id" = 175;
descr = "Ingredients are almonds or cashews. No hydrogenated stuff, no extra weirdo ingredients";
id = 107;
"multiple_images" = "Jellyfish.jpg,123.png";
name = "Butter Chicken";
price = 300;
rating = 3;
selected = 0;
"subcat_id" = 24;
"tag_id" = 43;
"tax_id" = 9;
"tax_value" = "0.00";
},
{
Image = "<UIImage: 0xf72f870>";
active = yes;
"admin_id" = 169;
"category_id" = 31;
"chef_id" = 173;
descr = "Raw vegetables including carrots, cucumbers.";
id = 100;
"multiple_images" = "Jellyfish.jpg,shake.png,";
name = Salads;
price = 50;
rating = 3;
selected = 0;
"subcat_id" = 22;
"tag_id" = 44;
"tax_id" = 9;
"tax_value" = "0.00";
}
Using predicates,
[array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"multiple_images CONTAINS '123'"]];
Using predicates, but with blocks
NSArray *filtered = [test filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:
^BOOL(NSDictionary *evaluatedObject, NSDictionary * bindings) {
NSString *key = #"123";
return ([evaluatedObject[#"multiple_images"] rangeOfString:key].location != NSNotFound);
}]];
Try
NSDictionary *item = mainArray[0];
NSString *imagesString = item[#"multiple_images"];
NSArray *images = [imagesString componentsSeparatedByString:#","];
Now you can use the images
Try this code
for (int i=0; i<[mainArray count]; i++) {
NSDictionary *item = [mainArray objectAtIndex:i];
NSString *imagesString = item[#"multiple_images"];
NSArray *images = [imagesString componentsSeparatedByString:#","];
for (int j=0;j<[images count]; j++) {
if ([[images objectAtIndex:j] isEqualToString:#"123.png"]) {
///Your Required code;
}
}
}
So you want to save the dictionary that has 123.png.
maybe you can try something like this:
NSMutableArray *arr = [NSMutableArray new];// your array of objects(dictionaries)
__block NSMutableArray *images123 = [NSMutableArray new];
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSMutableDictionary *dictionary = (NSMutableDictionary *)obj;
if([[dictionary allKeys]containsObject:#"multiple_images"]){
NSString *imageList = (NSString *)[dictionary objectForKey:#"multiple_images"];
NSArray *arrayImages = [imageList componentsSeparatedByString:#","];
if([arrayImages containsObject:#"123.png"]){
[images123 addObject:dictionary];
}
}
}];
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating non-repeating random numbers
Here is my code
NSUInteger count = 10;
for (NSUInteger i = 0; i < count; ++i) {
NSLog(#"%d",NeedRandomNumberWithoutRepeat);
}
this output should be like
8
7
9
2
1
4
6
3
5
0
Which is random and not repeating numbers
This should work:
NSUInteger count = 10;
NSMutableArray *array = [[NSMutableArray alloc]init];
for (NSUInteger i = 0; i < count; ++i) {
[array addObject:[NSNumber numberWithInt:i]];
}
NSMutableArray *copy = [array mutableCopy];
array = [[NSMutableArray alloc]init];
while ([copy count] > 0)
{
int index = arc4random() % [copy count];
id objectToMove = [copy objectAtIndex:index];
[array addObject:objectToMove];
[copy removeObjectAtIndex:index];
}
This answer is modified version from one of my answer in SO.
So, you may find something strange here, you can however use this as your requirement is similar.
int TOTAL_NUMBER=10;
NSMutableArray *alreadyGeneratedNumbers;
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification{
alreadyGeneratedNumbers=[NSMutableArray new];
}
-(int)generateRandomNumber{
int low_bound = 0;
int high_bound = TOTAL_NUMBER;
int width = high_bound - low_bound;
int randomNumber = low_bound + arc4random() % width;
return randomNumber;
}
- (IBAction)button:(id)sender {
NSMutableArray *shuffle = [[NSMutableArray alloc] initWithCapacity:1];
BOOL contains=YES;
while ([shuffle count]<1) {
NSNumber *generatedNumber=[NSNumber numberWithInt:[self generateRandomNumber]];
if (![alreadyGeneratedNumbers containsObject:generatedNumber]) {
[shuffle addObject:generatedNumber];
contains=NO;
[alreadyGeneratedNumbers addObject:generatedNumber];
}
}
NSLog(#"shuffle %#",shuffle);
NSLog(#"Next Batch");
if ([alreadyGeneratedNumbers count] >= TOTAL_NUMBER) {
NSLog(#"\nGame over, Want to play once again?");//or similar kind of thing.
[alreadyGeneratedNumbers removeAllObjects];
}
}
You put the available numbers in an array, and take the index calculated with arc4random() that goes from 0 to the size of the array -1.When a number comes out you take it away from the array:
NSMutableArray* availableNumbers=[NSMutableArray new];
for(NSUInteger i=0; i<10; i++)
{
[availableNumbers addObject: #(i)];
}
for(NSUInteger i=0; i<10; i++)
{
NSUInteger index= arc4random()%availableNumbers.count;
NSNumber* number= availableNumbers[index];
NSLog(#"%#",number);
[availableNumbers removeObjectAtIndex: index];
}
PS: At the last iteration is useless to sue arc4random(), since there's only one number inside.
I am making a game that assigns a label a question from a regular C array.
- (void)viewDidLoad
{
[super viewDidLoad];
for (int i = 0; i < 45; i++) {
basketball_numbers1[i] = (arc4random()%999)+100;
basketball_numbers2[i] = (arc4random()%999)+100;
for (int j = 0; j < 30; j++) {
int first = basketball_numbers1[i];
int second = basketball_numbers2[i];
basketball_questions[j] = [[NSString stringWithFormat: #"%d + %d", first, second] retain];
basketball_answers[j] = [[NSString stringWithFormat: #"%d", basketball_numbers1[i] + basketball_numbers2[i]] retain];
}
}
This code works and printed the questions and answers to the console no problem before I commented them out.
But when I'm running the emulator and type in the correct answer, the same questions stays on the label, even though the count (variable used to increase the index of the array) increases, which I confirmed via NSLog.
Some other notes: when I had manually put in values for the array, it worked no problem. Also I added in the 'retain' to the end of the array after doing some research, which actually eliminated some problems I was having before this, but I'm not sure if retain/release are used in regular C arrays or just NSArray.
Here is the code that reads in the textfield upon a button click.
- (IBAction)basketball_click:(id)sender {
basketball_input = self.basketball_textfield.text;
NSLog(#"INPUT: %#", self.basketball_textfield.text);
if ([self.basketball_textfield.text isEqualToString:(basketball_answers[count])]) {
NSLog(#"THEY ARE EQUAL");
isCorrect = TRUE;
self.basketball_textfield.text = #"";
}
...
if(isCorrect) {
NSLog(#"Retain Count: %d", [basketball_questions[count] retainCount]);
correct.text = #"CORRECT!";
basketball_right++;
count++;
NSLog(#"COUNT: %d", count);
question_label.text = basketball_questions[count];
NSLog(#"NEW QUESTION: %#", basketball_questions[count]);
}
for (int i = 0; i < 45; i++) {
first = (arc4random()%999)+100;
last = (arc4random()%999)+100;
basketball_questions[i] = [[NSString stringWithFormat: #"%d + %d", first, second] retain];
basketball_answers[i] = [[NSString stringWithFormat: #"%d", first+last] retain];
}
I am trying to assign a tag to button. The normal command is:
button.tag = 1;
The tag must be an integer.
My problem is that I would like to assign an integer which I stored in an array (tabReference) which is yet again part of a class (currentNoteBook). So I need this:
int k = 0;
button.tag = [currentNoteBook.tabReference objectAtIndex:k]; // This is where I get the warning.
This doesn't seem to work, however, as xCode tells me: Passing argument 1 of setTag: makes integer from pointer without a cast.
My array looks like this (I tried to use integers...):
NSMutableArray *trArray = [[NSMutableArray alloc] init];
NSNumber *anumber = [NSNumber numberWithInteger:1];
[trArray addObject: anumber];
[trArray addObject: anumber];
[trArray addObject: anumber];
[trArray addObject: anumber];
currentNoteBook.tabReference = trArray;
An NSMutableArray stores a modifiable array of objects. You can't directly store an integer in an NSMutableArray. That's why you have to do something like this to store a bunch of integers:
NSMutableArray *the_array = [[NSMutableArray alloc] init];
int max = 100;
for (int i = 0; i < max; i++)
{
NSNumber *temp_number = [NSNumber numberWithInt:arc4random() % max];
[the_array addObject:temp_number];
}
Of course, you could do pretty much the same thing and store something else in there:
NSMutableArray *the_array = [[NSMutableArray alloc] init];
int max = 100;
int max_x = 50;
int max_y = 25;
int max_w = 100;
int max_h = 200;
for (int i = 0; i < max; i++)
{
CGFloat temp_x = arc4random() % max_x;
CGFloat temp_y = arc4random() % max_y;
CGFloat temp_w = arc4random() % max_w;
CGFloat temp_h = arc4random() % max_h;
CGRect temp_rect = CGRectMake(temp_x, temp_y, temp_w, temp_h);
[the_array addObject:[NSValue valueWithCGRect:temp_rect]];
}
When you go to retrieve these values you need to specify what it is you want out of the array because the same array can contain very different objects.
For your integers:
for (int i = 0; i < max; i++)
{
NSLog(#"%i: %i", i, [[the_array objectAtIndex:i] intValue]);
}
For the CGRect example:
for (int i = 0; i < max; i++)
{
CGRect temp_rect = [[the_array objectAtIndex:i] CGRectValue];
NSLog(#"%i: x:%f y:%f w:%f h:%f", i, temp_rect.origin.x, temp_rect.origin.y, temp_rect.size.width, temp_rect.size.height);
}
In a nutshell, you are storing objects not integers in your code. You have to pull them out of there as objects and then extract your integer to get your data back.
Just found the answer in another question I posed:
it must be:
btn.tag = [[currentNoteBook.tabReference objectAtIndex:k] intValue];
I have a picker view controller to select a chemical source and possibly a concentration. If the source doesn't have concentrations, it just presents a single picker. It gets populated by an NSDictionary with source type names as keys and a custom model object I made called Chemical that has four properties, two NSString, one float and one BOOL.
When I trigger this with dictionary that has 2 components, I want to extract the four values from the Chemical that is represented. Note that I populate the picker with values from the first two properties, but not the float or BOOL. I run through the array for the key that's selected in the first component and check the string from the second component against the chemConcentration property from each of the Chemicals in the key/value array. When the chemConcentration matches, I know I have the right Chemical and I can get its properties to send back.
Whew!
The problem is that even though I know I get to the for loop, it seems to get skipped. The NSLog right before it prints, but the one inside doesn't. sourceConstant and sourceIsLiquid stay 0.0 and NO
- (IBAction)selectedSourceButton {
NSLog(#"selectedSourceButton pressed");
NSInteger sourceRow = [picker selectedRowInComponent:kSourceComponent];
NSString *selectedSource = [self.sources objectAtIndex:sourceRow];
NSArray *selectedChemicalGroup = [dictionaryOfSources objectForKey:selectedSource];
NSInteger concentrationRow = [picker selectedRowInComponent:kConcentrationComponent];
NSString *selectedConcentration = [[NSString alloc] init];
float selectedConstant = 0.0;
BOOL selectedIsLiquid = NO;
if (numberOfComponents == 2) {
NSLog(#"numberOfComponents = 2 if/then chosen"); // <-- This prints.
selectedConcentration = [self.concentrations objectAtIndex:concentrationRow];
NSLog(#"begin selectedConcentration for loop. Number of loops = %d", [selectedChemicalGroup count]); // <-- And so does this.
for (int i; i<[selectedChemicalGroup count]; i++) { // <-- But this doesn't seem to fire!
NSLog(#"selectedConcentration = %#, from selectedChemicalGroup = %#", selectedConcentration, [[selectedChemicalGroup objectAtIndex:i] chemConcentration]); // <-- Because this doesn't print.
if ([selectedConcentration isEqualToString:[[selectedChemicalGroup objectAtIndex:i] chemConcentration]]) {
selectedConstant = [[selectedChemicalGroup objectAtIndex:i] chemConstant];
selectedIsLiquid = [[selectedChemicalGroup objectAtIndex:i] chemIsLiquid];
}
}
}
else {
selectedConcentration = #"";
selectedConstant = [[selectedChemicalGroup objectAtIndex:0] chemConstant];
selectedIsLiquid = [[selectedChemicalGroup objectAtIndex:0] chemIsLiquid];
}
NSLog(#"selectedSourceButton source to return = %#, concentration = %#, sourceConstant = %1.7f, isLiquid = %d", selectedSource, selectedConcentration, selectedConstant, selectedIsLiquid);
if ([self.delegate respondsToSelector:#selector (sourcePickerViewController:didSelectSource:andConcentration:andConstant:andIsLiquid:)]) {
[self.delegate sourcePickerViewController:self didSelectSource:selectedSource andConcentration:selectedConcentration andConstant:selectedConstant andIsLiquid:selectedIsLiquid];
}
}
You need to initialize your variable i: for (int i = 0; ...
But there's a better way to do this, using "fast enumeration":
for (MyChemicalGroupClass *group in selectedChemicalGroup) {
if ([selectedConcentration isEqualToString:[group chemConcentration]]) {
...
}
}
Initialize loop count i
for (int i = 0; i<[selectedChemicalGroup count]; i++)
Do the following and you will understand why:
int i;
NSLog(#"%d", i);