I have an NSMutableDictionary that possibly contains more than twenty objects.
If it contains more than 20 objects, how should I remove the oldest entries until there is only 20 left?
For example, NSMutableDictionary with objects:
a = "-1640531535";
b = 1013904226;
c = "-626627309";
d = 2027808452;
e = 387276917;
f = "-1253254618";
g = 1401181143;
h = "-239350392";
i = "-1879881927";
With max number of objects: 5, should become:
a = "-1640531535";
b = 1013904226;
c = "-626627309";
d = 2027808452;
e = 387276917;
Thank you.
If all you're looking for is 20 elements, I'd try something like:
NSMutableDictionary* newDict = [NSMutableDictionary new];
int count = 0;
for (id theKey in oldDict)
{
[newDict setObject:[oldDict getObjectForKey:theKey] forKey:theKey];
if (++count == 20)
break;
}
[oldDict release];
oldDict = newDict;
The idea being that you copy the elements of the first 20 keys you find into a new dictionary, then replace the old one with the new one. If you want to iterate the dictionary via other means you could do that too, but the code above wouldn't have to change much.
If the keys are NSNumbers and you know they're sequential, and you want to remove the lower values, then:
int limit=20; //set to whatever you want
int excess = limit - [dict count];
if (excess > 0) {
for (int i = 1; i <= excess; i++) {
[dict removeObjectForKey:[NSNumber numberWithInt:i]];
}
}
If your keys are NSStrings then just create the NSString with the corresponding format.
If your keys are not sequential, then you would have to either have a parallel dictionary with the date of storage for each entry, so you would know when each entry was stored and you can remove the oldest, or you need to use something else entirely (if you are storing sequential integers as keys, wouldn't it be easier to use NSMutableArray?)
Related
I need to count same letters in a word. For example: apple is my word and first I found whether 'a' exists in this letter or not. After that I want to count the number of 'a' in that word but I couldn't do that. This is my code which finds the specific letter;
if([originalString rangeOfString:compareString].location==NSNotFound)
{
NSLog(#"Substring Not Found");
}
else
{
NSLog(#"Substring Found Successfully");
}
originalString is a word which I took from my database randomly. So, how to count?
Thanks for your help.
i have different idea let's try...
NSString *string = #"appple";
int times = [[string componentsSeparatedByString:#"p"] count]-1;
NSLog(#"Counted times: %i", times);
NSString *strComplete = #"Appleeeeeeeeeeeeeee Appleeeeeeeee Aplleeeeeeeeee";
NSString *stringToFind = #"e";
NSArray *arySearch = [strComplete componentsSeparatedByString:stringToFind];
int countTheOccurrences = [arySearch count] - 1;
Output :
countTheOccurrences --- 34
You could just loop over the string once, adding each letter to an NSMutableDictionary (as the key) and keeping a tally of how many times the letter occurs (as the value).
The resulting NSMutableDictionary would hold the number of occurences for each unique letter, whereby you can extract what you like.
I'm trying to create a grouped tableview, but when it comes to the number rows in sections I haven't been able to get the correct values. From the list below 'OrdreLinje', 'OrdreStatus' and 'KundeLeveranse' are the sections and the items below would be the rows visible to the user. So the number of rows in the sections would be 4,1,1 respectively, my question is how do I count these keys to produce the correct result.
Root(Dict)
-->Rows(Array)
---->Item 0(Dict)
------>OrdreLinje(Array)
-------->item0(Dict)
-------->item1(Dict)
-------->item2(Dict)
-------->item3(Dict)
------>KundeLeveranse(Array)
-------->item0(Dict)
------>OrdreStatus(Array)
-------->item0(Dict)
Sorry, I did try to insert an image but i'm not reputable enough :)
Any help is greatly appreciated,
B
Are you wanting a count of the keys in the first dictionary in the Rows array, or the sum of the keys in all the dictionaries in the Rows array?
For the first, you could do:
NSArray *rows = [rootDict objectForKey:#"Rows"];
NSInteger count = 0;
if (rows.count > 0)
{
NSDictionary *firstRow = [rows objectAtIndex:0];
count = firstRow.allKeys.count;
}
If you want the count of all keys in all dictionaries in the Rows array, you could do:
NSArray *rows = [rootDict objectForKey:#"Rows"];
NSInteger count = 0;
for (NSDictionary *dict in rows)
{
count += dict.allKeys.count;
}
I am trying to iterate through an NSArray with a for loop. The result only returns the last value in the array even though the int variable i is printing correctly (0,1,2...).
Also, if I set iteration to say 5, I will get the 6th object in the array, which is correct. I did this to try to narrow down the scope of possible causes.
Any ideas?
int i;
int j;
Buffer *vocalBuffer;
for (i=0; i < numberOfBuffers; i++){ // loop through every vocal buffer
Buffer *mixedBuffer = [[Buffer alloc] init];
int array[sizeLoopBuff];
mixedBuffer.buffer = array;
mixedBuffer.numFrames = sizeLoopBuff;
NSLog(#"Vocal buffer number --> %i", i);
NSInteger iteration = i;
vocalBuffer = [arrayOfVocalBuffers objectAtIndex:iteration]; // grab the vocal buffer
for (j=0; j < sizeLoopBuff; j++){ // run through a beat loop cycle.
mixedBuffer.buffer[j] = loopBuffer.buffer[j]; // add the beats to return buffer.
if (j > insertPoint && j < insertPoint+ vocalBuffer.numFrames){
mixedBuffer.buffer[j] = loopBuffer.buffer[j] + vocalBuffer.buffer[j-insertPoint];
}
}
[mutArray addObject:mixedBuffer];
}
As figured out in the comments, the use of a pointer to stack storage has some problems. One is that while it's in scope, its content is overwritten by each use within a loop; individual objects with pointers to it do not have unique copies.
The other problem is that once the method returns and its stack space isn't needed (as far as the runtime is concerned), there's no predicting what will be done with the space.
The necessary behavior of having a unique buffer per object suggests that the object should allocate its own buffer dynamically when created.
I'm building a game for iPhone, and I want to add 24 integers together. These 24 integers contain the total number of bombs ignited in each of the 24 levels. Here is the super crummy code i'm using right now:
totalBombs = level1bombs + level2bombs + level3bombs + level4bombs + level5bombs + level6bombs + level7bombs + level8bombs + level9bombs + level10bombs + level11bombs + level12bombs + level13bombs + level14bombs + level15bombs + level16bombs + level17bombs + level18bombs + level19bombs + level20bombs + level21bombs + level22bombs + level23bombs + level24bombs;
How can I simplify this code?
Yes, I realize this is very poor implementation. Please be gentle with your responses.
Make an array of the LevelBombs then do a loop over the array, adding them. In general, any time you have variables with names like
varname1
varname2
varname3
It means you need an array.
As others say, use an array, but an NS[Mutable]Array array is probably overkill for a collection of 24 integers - consider using a C array. E.g.
unsigned LevelBombs[24];
(assuming the number of bombs is never negative!). You can initialize a global like this using a literal:
unsigned LevelBombs[24] = { 27, 42, ..., 36 };
and you can omit the 24 if you do this - C can count. If you omit the size you get the count using:
unsigned count = sizeof(LevelBombs)/sizeof(unsigned);
Individual elements are LevelBombs[index] and a simple loop will give you the total.
Wrap the whole array up in a (singleton) class if you like, with appropriate methods to modify elements, get the total etc. But wrapping each element in an NSNumber and the whole lot in an NSMutableArray is probably just memory (de)allocation work you don't need.
I think you would benefit from using an array to store your bombs.
You could initialize the array in a couple different ways depending on what works best for your. One way would be like this which sets each level to 5.
int numLevels = 25;
NSMutableArray *bombs = [[NSMutableArray alloc] initWithObjects: nil];
for (int i = 0; i < numLevels; i++) {
[bombs addObject:[NSNumber numberWithInt:5]];
}
Or - if you want to initialize the array with different values for each level you would do something like this:
NSMutableArray *bombs = [[NSMutableArray alloc] initWithObjects: [NSNumber numberWithInt:5], [NSNumber numberWithInt:8], [NSNumber numberWithInt:10], [NSNumber numberWithInt:25], [NSNumber numberWithInt:55], [NSNumber numberWithInt:100], [NSNumber numberWithInt:200], nil];
And so on adding a new NSNumber for each level.
Then to access say level 1 you would do this:
NSNumber levelNumBombs = [bombs objectAtIndex:0];
or level 5 like:
NSNumber levelNumBombs = [bombs objectAtIndex:4];
To change level 5 bombs to 66 you would do something like this:
[bombs replaceObjectAtIndex:4 withObject:[NSNumber numberWithInt:66];
Then, to add everything up you would do something like this:
int totalBombs = 0;
for (int i = 0; i < [bombs count]; i++) {
totalBombs += [[bombs objectAtIndex:i] intValue];
}
i am trying to add individual integers to a certain array
my array is in this form
array= number +1
how can i make lets say number be a array = 2 +3 +1
where 2 and 3 are two different distinct obhects that should be commutatively added.
i hope i am clear. I dont want the numbers to be added so that the aboce equations would equal 0. i want it to be equal to 2 then 3 then 1....
NSMutableArray????
Do something like this:
int d = 0;
for (d = 0; i <100; i++)
{
[array addObject:[[NSString alloc] initWithFormat:#"%d", d]];
}
or whatever you want it to be
edit:
To add the numbers, just use intvalue