Increment a value in an int NSMutableArray - ios

I've an NSMutableArray as
self.valuesArray = [[NSMutableArray alloc]initWithObjects:[NSNumber numberWithInt: 0],[NSNumber numberWithInt: 0],[NSNumber numberWithInt: 0],[NSNumber numberWithInt: 0], nil];
As you can see it's initialized with 0 now If I want to increment 3 at index 2 how can I do it? I was trying to do it like
self.valuesArray[2] = [self.valuesArray objectAtIndex:2]+3;
but that's not the right way.
I've also tried doing this
[self.valuesArray[2] addObject:[NSNumber numberWithInt:[self.valuesArray[2] intValue]+3]];
but I got error that:
Unrecognized selector sent to instance

You should do like this it will work.
int valueInc = [[self.valuesArray objectAtIndex:2] intValue] + 2;
NSNumber *numberValue = [NSNumber numberWithInt:valueInc];
[self.valuesArray replaceObjectAtIndex:2 withObject:numberValue];

Related

sort array specified indexes IOS

I' want to filter NSARRAY based on an object named id, I've specific set of Ids that I want to filter and want to be first in NSARRAY.
I stored the following Ids as NSNUMEBR
NSNumber *A = [NSNumber numberWithInt:1122];
NSNumber *B = [NSNumber numberWithInt:1345];
NSNumber *C = [NSNumber numberWithInt:1667];
NSNumber *D = [NSNumber numberWithInt:1223];
NSNumber *E = [NSNumber numberWithInt:1213];
NSNumber *F = [NSNumber numberWithInt:1123];
NSNumber *G = [NSNumber numberWithInt:1555];
NSNumber *H = [NSNumber numberWithInt:1666];
NSNumber *I = [NSNumber numberWithInt:1567];
These are the set of ids that I want to filter and want to be first in my NSARRAY (Can be NSMutableArray for operation)
EDIT 1:
the NSARRAY is basically getting the id object as
Ids = [dict valueForKey:#"id"];
That selective ids are stored in NSNUMBER A to I
It is unclear what you are asking, as indicated by the down votes and comments. But let's see if we can help. I think the following pseudo-code algorithm is what you are asking for:
MutableArray frontItems, rearItems;
for every item in sourceArray
if item["id"] is in the collection of specific IDs
then add item to end of frontItems
else add item to end of rearItems
add rearItems to end of frontItems to give result
Write that in Objective-C and I think you have what you want.
HTH
//Creat array have all item : A->I
NSNumber *A = [NSNumber numberWithInt:1122];
NSNumber *B = [NSNumber numberWithInt:1345];
NSNumber *C = [NSNumber numberWithInt:1667];
NSNumber *D = [NSNumber numberWithInt:1223];
NSNumber *E = [NSNumber numberWithInt:1213];
NSNumber *F = [NSNumber numberWithInt:1123];
NSNumber *G = [NSNumber numberWithInt:1555];
NSNumber *H = [NSNumber numberWithInt:1666];
NSNumber *I = [NSNumber numberWithInt:1567];
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:A,B,C,...,I, nil];
for (NSNumber *idx in arr) {
// To do
}

Finding the lowest value and corresponding key in a large NSDictionary

I have a NSDictionary with NSString as keys and NSNumber as values such as the following
NSDictionary *dictionary = #{#"Apple" : [NSNumber numberWithInt: 6],
#"Banana" : [NSNumber numberWithInt: 1],
#"Peach" : [NSNumber numberWithInt: 14],
#"Lychee" : [NSNumber numberWithInt: 1]};
Here, I would like to find the lowest key and value, which in this example would be tie between Lychee : 1 and Banana: 1. Ordinarlly for a smaller dictionary, I would just sort through all the values as suggested by this answer and retrieve the first (or the tied) object in the array based on the ranking. However, I was wondering if there is a way to do it if the NSDictionary is very large, where I could just pluck the lowest key-value pairs?
Thanks!
As #Tommy said, there's no option other than to do a linear search. Sorting the dictionary will impose a function of O(n log(n)), while a linear search is obviously O(n). You'd need to use the following:
NSDictionary *dictionary = #{#"Apple" : [NSNumber numberWithInt: 6],
#"Banana" : [NSNumber numberWithInt: 1],
#"Peach" : [NSNumber numberWithInt: 14],
#"Lychee" : [NSNumber numberWithInt: 1]};
NSString *lowestKey = nil;
int lowestValue = 0;
for (NSString *key in dictionary)
{
int value = [dictionary[key] intValue];
if (!lowestKey || value < lowestValue)
{
lowestKey = key;
lowestValue = value;
}
}
NSLog(#"Lowest: %#: %d", lowestKey, lowestValue);
This code has several advantages: enumerateKeysAndObjectsUsingBlock: doesn't need to lookup any keys but accesses the keys and values directly from the dictionary's data structures, avoiding expensive lookups. Using an NSNumber compare operation makes the code work for large integers, fractional numbers and NSDecimalNumber.
__block NSString* lowestKey = nil;
__block NSNumber* lowestNumber = nil;
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, NSNumber* obj, BOOL *stop) {
if ([lowestNumber == nil || [obj compare:lowestNumber] == NSOrderedAscending)
{
lowestKey = key;
lowestNumber = obj;
}
}];
If there's no structure in place to avoid a linear search then you'll have to do a linear search.
E.g.
NSNumber *minValue = [[dictionary allValues] valueForKeyPath:#"#min.self"];
NSString *aLowestKey = [dictionary allKeysForObject:minValue][0];
That'll actually likely be two such searches; it'd be faster manually to iterate the keys and latch on the least key. But it'd be more and slightly more opaque code so pick based on where this code falls on the speed versus maintainability requirement curve.
(typed on an iPhone from a cafe; please forgive slight errors)

Add NSNumber 0 to NSDictionary

I need to create a dictionary with for a search, based on IDs, but if no ID gets selected, 0 has to be stored.
Now I can obviously do it like this:
NSNumber* cityID;
NSNumber* zoneID; //These two do get value, just showing for their class
NSDictionary *cityDictionary = #{#"CityID": [NSNumber numberWithInt:(int)cityId], #"CityZoneID": [NSNumber numberWithInt:(int)zoneId]};
I feel it's really messy like that. It gets cast to int, then turned back to NSNumber...
Try this
// May be syntax change but you need to initialise with zero first
NSNumber* cityID = [NSNumber numberWithInt:0];
NSNumber* zoneID = [NSNumber numberWithInt:0]; //Init with Zero then you can added value for this if no value default will be 0
NSDictionary *cityDictionary = #{#"CityID": [NSNumber numberWithInt:(int)cityId], #"CityZoneID": [NSNumber numberWithInt:(int)zoneId]};
This may help
What about
NSDictionary *cityDictionary = #{
#"CityID" : (cityID == nil ? #0 : cityID),
#"CityZoneID" : (zoneID == nil ? #0 : zoneID)
};
NSNumber* cityID;
NSNumber* zoneID;
if((cityID == nil)||(zoneID == nil))
{
NSDictionary *cityDictionary = #{#"CityID": [NSNumber numberWithInt:0], #"CityZoneID": [NSNumber numberWithInt:0]};
}

NSMutableArray insertObject at the index = 0 creating null pointers

I have a NSMutable array which i am storing some initial numbers. What I want to do is to be able to look at the numbers, and for some situations, remove that item and replace it with two more.
My insert/replace code seems to work when index > 0, however, when I try to insertObject AtIndex:0, it doesnt insert anything at 0, but places a null object at the end of the array.
To show the insert issue I can create an empty iOS Application.
I create the NSMutableArray as a property on the ViewController:
#property (strong) NSMutableArray *testArray;
And then in the implementation:
self.testArray = [[NSMutableArray alloc] init];
[self.testArray addObject: [NSNumber numberWithInteger:1]];
[self.testArray addObject: [NSNumber numberWithInteger:2]];
[self.testArray insertObject:[NSNumber numberWithInteger:3] atIndex:0];
If i place a break point after the insert, the debugger shows:
[0] = (id) 0x07123180 (int) 1
[1] = (id) 0x07614210 (int) 2
[2] = (id) 0x00000000
Where I was expecting to see an (int) 3 at place 0.
If I set atIndex:1, I get this:
[0] = (id) 0x07123180 (int) 1
[1] = (id) 0x07131fb0 (int) 3
[2] = (id) 0x07614210 (int) 2
Which is correct.
Why is index = 0 not working?
Works for me:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSMutableArray *testArray = [[NSMutableArray alloc] init];
[testArray addObject: [NSNumber numberWithInteger:1]];
[testArray addObject: [NSNumber numberWithInteger:2]];
[testArray insertObject:[NSNumber numberWithInteger:3] atIndex:0];
for (NSNumber *num in testArray)
NSLog(#"%#", num);
}
return 0;
}
2013-09-15 09:51:18.266 ArrayTest[890:303] 3
2013-09-15 09:51:18.269 ArrayTest[890:303] 1
2013-09-15 09:51:18.269 ArrayTest[890:303] 2
Program ended with exit code: 0
If I break on the for statement and use lldb:
(lldb) po testArray
<__NSArrayM 0x100109120>(
3,
1,
2
)
(this was using Xcode 5 DP 6 under Mavericks DP 7).
Works for me
testArray = [[NSMutableArray alloc]init];
[testArray addObject:[NSNumber numberWithInt:1]];
[testArray addObject:[NSNumber numberWithInt:2]];
[testArray insertObject:[NSNumber numberWithInt:0] atIndex:0];
NSLog(#"%#",testArray);
Log
2013-09-15 10:53:39.048 JsonExample[79141:a0b] (
0,
1,
2
)
I copied your sample code too and it works fine in Xcode 4

Iterating through a Dictionary

I'm trying to iterate over an NSMutableDictionary and I cannot seem to get what I want. I have a dictionary mapping strings to colors like so...
squareColors = [NSMutableDictionary dictionaryWithObjects: [NSMutableArray arrayWithObjects:
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:0],
nil]
forKeys: [NSMutableArray arrayWithObjects:
#"yellow",
#"blue",
#"green",
#"purple",
#"orange",
nil]];
Over time the value of each entry will increase. Every once in a while I want to look into the dictionary and select the color with the highest count. How might I do that? Here's what I'm trying, but I'm unfamiliar with blocks.
__block int mostSquares = 0;
__block NSString* color = #"";
/* Look through the dictionary to find the color with the most number of squares */
[squareColors enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(#"%# => %#", key, obj);
NSInteger count = [key integerValue];
if (count > mostSquares)
{
color = key;
mostSquares = count;
}
}];
You have a very simple bug in your code. This line:
NSInteger count = [key integerValue];
should be:
NSInteger count = [obj integerValue];
'key' is the color name, obj is the number. As you have it, count gets set to 0 for each iteration because calling integerValue on a non-numeric string gives you 0.
Simple solution using your example:
NSMutableArray *arrayNumbers = [NSMutableArray arrayWithObjects:
[NSNumber numberWithInt:0],
[NSNumber numberWithInt:1],
[NSNumber numberWithInt:2],
[NSNumber numberWithInt:6],
[NSNumber numberWithInt:4],
nil];
NSMutableArray *arrayColours = [NSMutableArray arrayWithObjects:
#"yellow",
#"blue",
#"green",
#"purple",
#"orange",
nil];
NSMutableDictionary *squareColors = [NSMutableDictionary dictionaryWithObjects:arrayNumbers
forKeys:arrayColours];
NSUInteger indexOfArray = [arrayNumbers indexOfObject:[arrayNumbers valueForKeyPath:#"#max.intValue"]];
NSLog (#"Colour with largest value is %#", [arrayColours objectAtIndex:indexOfArray]);
Can you store your Keys into an array and iterate using that array? That would probably be the most efficient solution, since you'll need to know every key anyway.

Resources