Insert few objects from an array in nsmutable dictionary - iphone

I am having an array of 30 Images i want to add only 15 images to nsmutable dictionary and which are to be added randomly
I am using the following code
for (m = 0; m < 20; m++)
{
rnd = arc4random_uniform(FrontsCards.count);
dic=[[NSMutableDictionary alloc]init];
[dic setObject:[NSNumber numberWithInt:rnd] forKey:#"Images"];
NSLog(#"%#",dic);
}
here the problem is as for m=0 entry gets in dictionary ,for m=1 again an entry goes in dictionary replacing first one and at the end i get only the last value the desired output is all the 20 values can anybody help me out..
Thanks in advance...

You are using the SAME TAG "Images" for every number you set. Hence it gets replaced again and again
dic=[[NSMutableDictionary alloc]init];
for (m = 0; m < 20; m++)
{
rnd = arc4random_uniform(FrontsCards.count);
[dic setObject:[NSNumber numberWithInt:rnd] forKey:[NSString stringWithFormat:#"Images_%d",rnd];
}
NSLog(#"%#",[dic description]);

In this case you need to use NSMutableArray because you are using again and again same key so last value will be replace by new value. So there are 2 option
1) First use different Key for every image.
2) You can use NSMutableArry to add new object.

I found many problem in your code:
1. You want to add 15 images but make loop of 20;
2. You are creating Dictionary in side loop so it will created 20 time. Each time new Dictionary is created and old one get deleted.
3. You ar using same key to store all value. You have to use unique key for each item. Other wise old itel get replaced
Use Like this
dic=[[NSMutableDictionary alloc]init];
for (m = 0; m < 15; m++)
{
rnd = arc4random_uniform(FrontsCards.count);
[dic setObject:[NSNumber numberWithInt:rnd] forKey:[NSString stringWithFormat#"Image%d",rnd]];
}
NSLog(#"%#",dic);

You are allocating new dic evrytime. So it gets overwritten. Try this. Also as mayur said you cant use same key.
dic=[[NSMutableDictionary alloc]init];
for (m = 0; m < 20; m++)
{
rnd = arc4random_uniform(FrontsCards.count);
[dic setObject:[NSNumber numberWithInt:rnd] forKey:[NSString stringWithFormat:#"Images_%d",rnd]];
}
NSLog(#"%#",dic);

You cannot enter more than one object or image with the same key... Here the key is set as Images. So the value for the key named images will be set again and again... Either you have to specify different name for key in each case or use an array to store all images.
Also declare the dictionary outside the for loop. Try the below code.
dic=[[NSMutableDictionary alloc]init];
for (m = 0; m < 20; m++)
{
rnd = arc4random_uniform(FrontsCards.count);
[dic setObject:[NSNumber numberWithInt:rnd] forKey:#"Images_%d", m];
NSLog(#"%#",dic);
}

Above Answer is Right You follow this code and solve your problem.

Related

Questions app without repetition

I want to make a question app which shows a random question from a plist I made. This is the function (there are only 7 questions for now).
My function gives a random question but it always starts with the same question
and a question can be repeated. I need your help to generate the question randomly and without repetition.
currentQuestion=rand()%7;
NSDictionary *nextQuestion = [self.questions objectAtIndex:currentQuestion];
self.answer = [nextQuestion objectForKey:#"questionAnswer"];
self.qlabel.text = [nextQuestion objectForKey:#"questionTitle"];
self.lanswer1.text = [nextQuestion objectForKey:#"A"];
self.lanswer2.text = [nextQuestion objectForKey:#"B"];
self.lanswer3.text = [nextQuestion objectForKey:#"C"];
self.lanswer4.text = [nextQuestion objectForKey:#"D"];
rand()%7; will always produces a unique sequence of random numbers.
Use arc4random() % 7; instead.
currentQuestion=arc4random() %7;
I'd do it this way (in ARC, written out extra long for clarity):
#property (nonatomic,strong) NSDictionary *unaskedQuestions;
- (NSString *)nextRandomUnaskedQuestion {
if (!self.unaskedQuestions) {
// using your var name 'nextQuestion'. consider renaming it to 'questions'
self.unaskedQuestions = [nextQuestion mutableCopy];
}
if ([self.unaskedQuestions count] == 0) return nil; // we asked everything
NSArray *keys = [self.unaskedQuestions allKeys];
NSInteger randomIndex = arc4random() % [allKeys count];
NSString *randomKey = [keys objectAtIndex:randomIndex];
NSString *nextRandomUnaskedQuestion = [self.unaskedQuestions valueForKey:randomKey];
[self.unaskedQuestions removeObjectForKey:randomKey];
return nextRandomUnaskedQuestion;
}
Use an array of your question keys. Say you have array named arrKeys --> [A], [B], [C], [D], ... , [z], nil
Use (arc4random() % array.length-1) {as suggested by Suresh} to generate rendom index for your array. Say you got rand = 3
Get the key from array arrKeys #3 = D. Then from your NSDictionary use [nextQuestion objectForKey:#"D"] and also remove the 'D' key from your array as [arrKeys removeObjectAtIndex:3]. Repeat 1-3 steps for next question.

Store score at the time of completing game & get data on HighScore button press in iphone

I have done this code to store score.
But this is giving me the last added score only, not storing data every time on new index.
-(IBAction)btnSaveScore:(id)sender
{
if(!dictWinData)
dictWinData = [[NSMutableDictionary alloc] init];
array = [NSMutableArray arrayWithObjects:txt_EnterName.text,
[NSString stringWithFormat:#"%i",iTap], nil];
int increment = 0;
NSLog(#"array data is:--> %#",array);
for (int intWinData = 1; intWinData < [array count]; intWinData++)
{
[dictWinData setObject:array forKey:[NSString stringWithFormat:#"NameScore%d",increment]];
increment++;
}
}
If any mistake is there in my code then please let me guide for this.
Is there anyother way to store the data..?
Is NSUserDefaults helpful to store & display data...?
How to use NSUserDefaults to store & retrive data.
Thanks.
The issue is with this line:
int increment = 0;
Every time you press the save button the increment will be initialized to zero and hence every time the value is added to dictionary for same key NameScore0. Hence it will over write the existing dictionary value.
You need to make the increment as static like static int increment = 0; or make it as a global variable, it will solve the issue.
-(IBAction)btnSaveScore:(id)sender
{
if(!dictWinData)
dictWinData = [[NSMutableDictionary alloc] init];
array = [NSMutableArray arrayWithObjects:txt_EnterName.text,
[NSString stringWithFormat:#"%i",iTap], nil];
static int increment = 0;
for (int intWinData = 1; intWinData < [array count]; intWinData++)
{
[dictWinData setObject:array forKey:[NSString stringWithFormat:#"NameScore%d",increment]];
increment++;
}
}
NSUserDefaults is used for displaying the application setting in the ios device's settings pane. Don't save your application data there.
Instead of NSUserDefaults you can use plist to store data.
Please check the link

Create an unknown number of objects

I need to create a specific number instances of an object based on a variable. so the pseudo code looks kinda like this
for(int x; x < aInt; x++) {
//create object and initialize it
}
how would I do that and create a different object each time with a different name and memory location?
Stick the reference in a NSMutableArray (or a NSArray, given that you appear to know the size in advance).
NSMutableArray *array = [[NSMutableArray alloc]init]
for(int x; x < aInt; x++) {
//create object and initialize it
YourObject *o = [[YourObject alloc]init];
[array addObject:o];
[o release];
}
// do whatever you need to do with the objects
A NSDictionary/NSMutableDictionary is certainly an option as well, depending on what your requirements are.
Just use a NSMutableArray:
NSMutableArray *objectsArray = [NSMutableArray arrayWithCapacity:(YourIntegerValue)];
for(int x; x < aInt; x++) {
//create object and initialize it
[objectsArray addObject:(YourObject)];
}
Don't forget to release the array after you're done working with it!

NSInteger to NSArray iPhone

I have NSInteger variable, for example NSInteger example=1256 and i need an array with elements of this variable.
so first element of array is array[0] = 1
array[1] = 2
array[2] = 5 etc..
what way can i solve it ?
Here's about how I'd do it:
NSUInteger number = 1234567890;
NSMutableArray * numbers = [NSMutableArray array];
while (number > 0) {
NSUInteger lastDigit = number % 10;
[numbers insertObject:[NSNumber numberWithUnsignedInteger:lastDigit] atIndex:0];
number = number / 10;
}
You need to use NSMutableArray to be able to change entries. NSMutableArray can only hold objects, not primitive types like NSInteger. Also, if you are using NSMutableArray, you can't access the elements the same way as with a C array.
[array insertObject:[NSNumber numberWithInteger:2] atIndex:1];
You can convert your integer to a char* then iterate through it casting each character back to an int and adding it to a C array or, as Steven says, an NSArray of NSNumbers.

iphone Development - pick unique image from array problem, syntax help

Code:
//pick one filename
int numFileNames = [imageArray count];
int chosen = arc4random() % numFileNames;
NSString *oneFilename = [imageArray objectAtIndex: chosen];
thanks!!
There's one error in your NSMutableArray:
You need to initialize it first.
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
;)
and here's a suggestion, if you do not necessarily require the interface builder's assistance, you might want to consider cocos2d. The stuffs you wanted to do can be done easily in it.
--
as for step 3. Do a random pick using Rand(), make a loop to check if the selected image is already added in an array (this array is for picked images), if it's in the array randomize again, if not then add in into the picked array, and do ball1.image = [UIImage imageNamed:[imageArray objectatindex:randomNum]];
The question does not specify the issue at hand, it just mentions that the developer wants to store a unique image name in array, so coding can be done:
NSMutableArray *arrImages = [NSMutableArray new];
for (int i=0; i<2; i++) {
NSString *imgName = [NSString stringWithFormat:#"imageBall%d",i];
//Here we can check whether image is already added or not.
if (![arrImages contains Object:imgName]) {
[arrImages addObject:imgName];
}
}
int choosen = arc4random() % (int)arrImages.count;
NSString *imageFileName = arrImages[choosen];