Get Integer value from NSNumber in NSArray - objective-c

I have an NSArray with NSNumber objects that have int values:
arrayOfValues = [[[NSArray alloc] initWithObjects: [NSNumber numberWithInt:1], [NSNumber numberWithInt:3], [NSNumber numberWithInt:5], [NSNumber numberWithInt:6], [NSNumber numberWithInt:7], nil] autorelease];
[arrayOfValues retain];
I'm trying to iterate through the array like this:
int currentValue;
for (int i = 0; i < [arrayOfValues count]; i++)
{
currentValue = [(NSNumber *)[arrayOfValues objectAtIndex:i] intValue];
NSLog(#"currentValue: %#", currentValue); // EXE_BAD_ACCESS
}
What am I doing wrong here?

You are using the wrong format specifier. %# is for objects, but int is not an object. So, you should be doing this:
int currentValue;
for (int i = 0; i < [arrayOfValues count]; i++)
{
currentValue = [(NSNumber *)[arrayOfValues objectAtIndex:i] intValue];
NSLog(#"currentValue: %d", currentValue); // EXE_BAD_ACCESS
}
More information in the docs.

This worked for me when creating an NSArray of enum values I wanted to call (which is useful to know that this is the proper solution for that) I'm using Xcode 6.4.
int currentValue = (int)[(NSNumber *)[arrayOfValues objectAtIndex:i] integerValue];
sosborn's answer will throw a warning since it is still necessary to cast the NSInteger to an int.
Typecasting in ObjC is the bane of my existence. I hope this helps someone!

Related

How to multiply respective objects of NSArray and get the sum?

I have one array with data A=[a,b,c] and another with data B=[d,e,f]. I need to perform this type of operation a.d+ b.e+c.f (Note=Here (.) denotes multplication)and get the result. How can i do that using Objective-C?
Thanks in advance.
Define the function that does the multiplication and addition like this:
- (double)multiply:(NSArray <NSNumber *> *)vector1 withVector:(NSArray <NSNumber *> *)vector2 {
NSAssert(vector1.count == vector2.count, #"Both arrays should contain the same number of elements");
__block double result = 0;
[vector1 enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
double first = obj.doubleValue;
double second = vector2[idx].doubleValue;
result += first * second;
}];
return result;
}
This uses a block enumeration method on NSArray which gives me in index and a value, which I can use to get the value at the same index in the second array. Note also that I am using a typed array, so I don't have to cast the values to NSNumbers when using them.
Now you can just use the function:
NSArray *a = #[#1, #2, #3];
NSArray *b = #[#4, #5, #6];
NSArray *c = #[#1, #1, #1];
double res1 = [self multiply:a withVector:b]; // => 32.000000
double res2 = [self multiply:b withVector:c]; // => 15.000000
double res3 = [self multiply:c withVector:a]; // => 6.000000
NSNumber *myNum1 = [NSNumber numberWithInt:1];
NSNumber *myNum2 = [NSNumber numberWithInt:2];
NSNumber *myNum3 = [NSNumber numberWithInt:3];
NSArray *a = [NSArray arrayWithObjects: myNum1, myNum2, myNum3, nil];
NSArray *b = [NSArray arrayWithObjects: myNum1, myNum2, myNum3, nil];
int sum=0;
for (int i=0; i<[a count]; i++) {
NSLog(#"%#", (NSNumber*)[a objectAtIndex:i]);
sum =sum +[(NSNumber*)[a objectAtIndex:i] intValue]*[(NSNumber*)[b objectAtIndex:i] intValue];
}
NSLog(#"Sum is %d", sum);
Hope this helps

NSTableColumn sorts numbers wrongly

This is a NSTableView with IB bindings to a NSArrayController, it displays all values correctly.
However it sorts the numbers only by their first char value e.g. it will put 115.31 below 2.5, and 23.9 below 4.71, etc.
It takes values from a retained NSMutableArray with Strings in it, I also tried by converting all strings to NSNumber/NSDecimalNumber, still no luck:
NSMutableArray *array1 = [[string1 componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]] mutableCopy];
NSMutableArray *array1alt = [NSMutableArray array];
for(NSString *strNum in array1)
{
NSNumber *number = strNum;
[array1alt addObject:number];
}
Please help, thanks.
EDIT: This is how NSMutableArray(s) of my NSTableColumn(s) get filled:
NSMutableArray *rows = [NSMutableArray array];
for (NSUInteger i = 0; i < array1alt.count && i < array2.count && i < array3.count && i < array4.count; i++)
{
NSMutableDictionary *row = [NSMutableDictionary dictionary];
[row setObject:[array1alt objectAtIndex:i] forKey:#"Apples"];
[row setObject:[array2 objectAtIndex:i] forKey:#"Oranges"];
[row setObject:[array3 objectAtIndex:i] forKey:#"Peaches"];
[row setObject:[array4 objectAtIndex:i] forKey:#"Plums"];
[rows addObject:row];
}
[myArrayController2 setContent:rows2];
[aTableView reloadData];
I'm surprised that you aren't getting a compiler warning at:
NSNumber *number = strNum;
You probably want:
NSNumber *number = [NSNumber numberWithDouble:[strNum doubleValue]];
Or, more simply:
NSNumber *number = #([strNum doubleValue]);
If you don't want to deal with number conversions on the output, you could sort your original array of strings like so:
NSArray *array2 = [array1 sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {
double num1 = [obj1 doubleValue];
double num2 = [obj2 doubleValue];
if (num1 < num2)
return NSOrderedAscending;
else if (num1 > num2)
return NSOrderedDescending;
else
return NSOrderedSame;
}];
If you want to use decimal numbers, you could probably do something like:
NSMutableArray *array2 = [NSMutableArray array];
for (NSString *strNum in array1)
{
[array2 addObject:[NSDecimalNumber decimalNumberWithString:strNum]];
}
[array2 sortUsingComparator:^NSComparisonResult(NSDecimalNumber *obj1, NSDecimalNumber *obj2) {
return [obj1 compare:obj2];
}];
Without seeing more code this is what i think:
If i understood correctly, you have your NSArrayController as data source.
You need to sort your data before attaching it to your table.
You have NSArrayController methods:
- (void)setSortDescriptors:(NSArray *)sortDescriptors
and
- (NSArray *)arrangeObjects:(NSArray *)objects
With this you will get sorted array to use for your table.
Maybe you will need to call reloadData of your NSTableView.
I cant test these right now because i'm at my laptop right now which doesn't have MacOS :)

How to exclude previously randomly selected NSArrays in loop

I'm new to Objective-C and I'm trying to create a simple dictionary style app for personal use. Right now I'm attempting to make a loop that prints randomly selected NSArrays that have been added to an NSDictionary. I'd like to print each array only once. Here is the code I'm working with:
NSArray *catList = [NSArray arrayWithObjects:#"Lion", #"Snow Leopard", #"Cheetah", nil];
NSArray *dogList = [NSArray arrayWithObjects:#"Dachshund", #"Pitt Bull", #"Pug", nil];
...
NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init];
[wordDictionary setObject: catList forKey:#"Cats"];
[wordDictionary setObject: dogList forKey:#"Dogs"];
...
NSInteger keyCount = [[wordDictionary allKeys] count];
NSInteger randomKeyIndex = arc4random() % keyCount;
int i = keyCount;
for (i=i; i>0; i--) {
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
NSLog(#"%#", randomlySelectedArray);
}
This code prints the same array "i" times. Any pointers on how to exclude previously printed arrays from being printed again?
I'm wondering if removeObjectForKey: could be of any use.
You just need to re-calculate the random key index every time you go through the loop, and then, as you suggest, use removeObjectForKey:.
Something like this:
NSArray *catList = [NSArray arrayWithObjects:#"Lion", #"Snow Leopard", #"Cheetah", nil];
NSArray *dogList = [NSArray arrayWithObjects:#"Dachshund", #"Pitt Bull", #"Pug", nil];
//...
NSMutableDictionary *wordDictionary = [[NSMutableDictionary alloc] init];
[wordDictionary setObject: catList forKey:#"Cats"];
[wordDictionary setObject: dogList forKey:#"Dogs"];
//...
while ([wordDictionary count] > 0) {
NSInteger keyCount = [wordDictionary count];
NSInteger randomKeyIndex = arc4random() % keyCount;
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
NSLog(#"%#", randomlySelectedArray);
[wordDictionary removeObjectForKey: randomKey];
}
In your code, you generate a random randomKeyIndex, then use it without changing its value i times in the loop. So you get i times the same array.
NSInteger randomKeyIndex = arc4random() % keyCount;
// ...
for (i=i; i>0; i--) {
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
// ...
}
As you say removeObjectForKey is an option for you, you can change your code into something like this:
NSInteger keyCount = [[wordDictionary allKeys] count];
for (i=keyCount; i>0; i--) {
NSInteger randomKeyIndex = arc4random() % keyCount;
NSString *randomKey = [[wordDictionary allKeys] objectAtIndex:randomKeyIndex];
NSMutableArray *randomlySelectedArray = [wordDictionary objectForKey:randomKey];
[wordDictionary removeObjectForKey:randomKey];
keyCount--;
NSLog(#"%#", randomlySelectedArray);
}

Populating array with integers

Let's say I want to populate NSarray with 50 integers. We know that NSarray accept only objects. So I have to do 50 times
NSNumber *num1 = [NSNumber numberWithInit:10];
NSNumber *num2 = [NSNumber numberWithInit:212];
......
NSNumber *num50 = [NSNumber numberWithInit:12];
Is there more elegant way to achieve that, beacause looks stupid 50 lines of code only for create number objects ?
try this...
NSMutableArray *array=[[NSMutableArray alloc]initWithCapacity:50 ];
for (int i=0; i<0; i++) {
NSNumber *number=[[NSNumber alloc] initWithInt:i];
[array addObject:number];
[number release];
}
//do anything with arrray and release the array later.
is this OK or you are seeking anything else.?
How about using NSMutableArray?
NSMutableArray* arr = [[NSMutableArray alloc] init];
int i = 0;
for(i=0; i<50; i++) {
NSNumber* num = [NSNumber numberWithInt:i]; // use i or random numbers
[arr addObject:num];
}
Your numbers do not seem to follow any particular pattern, so you might be better doing this by creating a C array first:
int myValues[] = { 10, 212, ..., 12 };
NSUInteger count = sizeof(myValues)/sizeof(int); // number of integers in myValues
// abstract the following into a function/method/category if doing more than once
NSMutableArray *objcValues = [NSMutableArray arrayWithCapacity:count];
for(NSUInteger ix = 0; ix < count; ix++)
[objcValues addObject:[NSNumber numberWithInt:myValues[ix]];

Assigning an arrays count to an int, NSNumber or NSUInteger fails

Assigning an int, NSNumber and NSUInteger to an arrays count fails...
this is my line of code
int diamondCount = [diamonds count];
where diamonds is an nsarray
I built the app and it threw an EXC_BAD_ACESS on that line
So i looked at the NSArray count method and found it returns an nsuinteger
So i did:
NSUInteger diamondCount = [diamonds count];
that still threw me EXC_BAD_ACCESS so at last resort i assigned it to an nsnumber with numberWithInteger:
it stilled crashed.... any thoughts?
diamonds does not point to a real (and valid) NSArray. Check its initialization.
Try this:
NSArray *myArray;
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = #"a string";
myArray = [NSArray arrayWithObjects:aDate, aValue, aString, nil];
int i = [myArray count];
NSLog(#"%d",i);
NSInteger j = [myArray count];
NSLog(#"%d",j);
NSNumber *k = [myArray count];
NSLog(#"%d",k);
/*output
2011-11-21 17:01:48.272 test[48840:1303] 3
2011-11-21 17:01:48.272 test[48840:1303] 3
2011-11-21 17:01:48.273 test[48840:1303] 3*/