The code below produces and error in the line [myArray objectAtIndex:i]; and I can't seem to figure out why?
Any ideas?
int total = 0;
for (int i = 0; i < myArray.count; i++) {
int tempNumber = [myArray objectAtIndex:i];
total = total + tempNumber;
}
It could be because you are setting an object to an int. By definition, objectAtIndex returns an object.
Depending on the type of object in myArray, you can try something like this:
int tempNumber = [[myArray objectAtIndex:i] intValue];
If you didn't put ints into your array, then you need to do something extra to get ints out. If you're getting an error with your code above, then it's because you don't have ints in the array, and you need
int myInteger = [[myArray objectAtIndex:i] intValue];
Or something to get the ints out of the array, depending on the rest of your code.
Related
Question:
Find the value of K in myInterViewArray without any messages/calls
I was given this hint:
The numbers in the array will never exceed 1-9.
NSArray *myInterViewArray = #[#2,#1,#3,#9,#9,#8,#7];
Example:
If you send 3, the array will return the 3 biggest values in myInterViewArray * 3. So in the example below, K = 9 + 9 + 8.
--
I was asked this question a while back in an interview and was completely stumped. The first solution that I could think of looked something like this:
Interview Test Array:
[self findingK:myInterViewArray abc:3];
-(int)findingK:(NSArray *)myArray abc:(int)k{ // With Reverse Object Enumerator
myArray = [[[myArray sortedArrayUsingSelector:#selector(compare:)] reverseObjectEnumerator] allObjects];
int tempA = 0;
for (int i = 0; i < k; i++) {
tempA += [[myArray objectAtIndex:i] intValue];
}
k = tempA;
return k;
}
But apparently that was a big no-no. They wanted me to find the value of K without using any messages. That means that I was unable to use sortedArrayUsingSelector and even reverseObjectEnumerator.
Now to the point!
I've been thinking about this for quite a while and I still can't think of an approach without messages. Does anyone have any ideas?
There is only one way to do that and that is bridging the array to CF type and then use plain C, e.g.:
NSArray *array = #[#1, #2, #3];
CFArrayRef cfArray = (__bridge CFArrayRef)(array);
NSLog(#"%#", CFArrayGetValueAtIndex(cfArray, 0));
However, if the value is a NSNumber, you will still need messages to access its numeric value.
Most likely the authors of the question didn't have a very good knowledge of the concept of messages. Maybe they thought that subscripting and property access were not messages or something else.
Using objects in Obj-C without messages is impossible. Every property access, every method call, every method initialization is done using messages.
Rereading the question, they probably wanted you to implement the algorithm without using library functions, e.g. sort (e.g. you could implement a K-heap and use that heap to find the K highest numbers in a for iteration).
I assume what is meant is that you can't mutate the original array. Otherwise, that restriction doesn't make sense.
Here's something that might work:
NSMutableArray *a = [NSMutableArray array];
for (NSNumber *num in array) {
BOOL shouldAdd = NO;
for (int i = a.count - 1; i >= k; i--) {
if ([a[i] intValue] < [num intValue]) {
shouldAdd = YES;
break;
}
}
if (shouldAdd) {
[a addObject:num];
}
}
int result = a[a.count - k];
for (int i = k; k < a.count; k++) {
result += [a[i] intValue];
}
return result;
If I have an NSArray, and I want to get each of the numbers in it, is there a simple way to do that?
I tried the advice from
http://code.flamingleaf.com/category/objective-c/
that said instead of (the method used in other programming languages for subscripts within arrays):
someArray[i]
to use
[someArray objectAtIndex:i];
Is there some way to get the numeric value?
I keep getting an error of the type:
“Subscript requires size of interface 'NSArray', which is not constant in non-stable ABI”
Thank you for the suggestion by Kurt Revis to put in real code. I could not recreate the problem. But this is my closest:
for (int i=0; i<4; i++)
NSLog(#"%i",[[temp objectAtIndex: i]length]);
for (int i=0; i<4; i++)
tempNumbers[i]=[[temp objectAtIndex:i] length];
for (int i=0; i<4; i++)
NSLog(#"The count at i=%i is %i", i, tempNumbers[i]);
and it worked as:
3
3
5
2
the value of i = 0 and tempNumbers[i]=3.000000
the value of i = 1 and tempNumbers[i]=3.000000
the value of i = 2 and tempNumbers[i]=5.000000
the value of i = 3 and tempNumbers[i]=2.000000
Conclusion: Until I can write simple code to recreate the problem, I won't clog this question area.
2nd Conclusion: I will try the solution suggested by edc1591.
It's hard to tell without seeing what class the objects are, but if they are of type NSString or NSNumber you can use any of the following methods to get the numerical value:
[[someArray objectAtIndex:i] floatValue];
[[someArray objectAtIndex:i] doubleValue];
[[someArray objectAtIndex:i] intValue];
[[someArray objectAtIndex:i] unsignedIntValue];
etc...
I need to convert a string like '00120' into an NSArray of NSIntegers.
can you please help?
Thanks
Try this code out:
NSString *input = #"00120";
NSMutableArray *integers = [NSMutableArray array];
for (int i = 0; i < input.length; i++) {
unichar c = [input characterAtIndex:i];
if (!isnumber(c))
[integers addObject:[NSNumber numberWithInt:-1]];
else
[integers addObject:[NSNumber numberWithInt:c - '0']]; // convert the ASCII value to it's integer counterpart.
}
This is, of course, assuming all of your characters are numbers in the string.
EDIT: If you want a NSInteger, you need to make a C-Array:
NSString *input = #"00120";
NSInteger *integers = calloc(input.length, sizeof(NSInteger));
NSInteger integersLen = input.length;
for (int i = 0; i < input.length; i++)
{
unichar c = [input characterAtIndex:i];
if (!isnumber(c))
integers[i] = -1;
else
integers[i] = c - '0'; // convert the ASCII value to it's integer counterpart
}
Everything you need to know can be found in the class reference for NSString and NSMutableArray. Look up a tutorial on for loops if you're not familiar with them already.
Notable methods that you're likely to want to use are -length and -characterAtIndex: on NSString, and -addObject: / -insertObject:atIndex: on NSMutableArray.
I don't mean to come across as patronising, but I'm not going to write out the code for you here as you'll learn much more if you work it out yourself with some help. Please do feel free to update the question with your code if you get stuck and ask for more specific help.
How would you go about storing a 2 dimensional array of ints as a class variable?
If you want an array of ints you go:
Class declaration
int * myInts;
Implementation
int ints[3] = {1,2,3};
myInts = ints;
But what if you want to store an array of arrays with ints?
Like this:
int ints[3][3] = {{1,2,3}, {1,2,3}, {1,2,3}};
I don't wanna limit the size of the arrays in the class declaration so I guess I have to go with pointers, but how?
For future reference, this is my conclusion:
Class declaration
int ** ints;
Implementation
int rows = 2;
int cols = 5;
ints = (int**)malloc(rows*sizeof(int*));
ints[0] = (int*)malloc(cols*sizeof(int));
ints[0][0] = 123;
ints[0][1] = 456;
ints[0][2] = 789;
// etc
This is my own interpretation of links provided in comments and my C skills are pretty low so take that into consideration ;) Maybe there are better ways to put in multiple numbers at a time with {123,456,789} or something, but that is beyond my requirements for now!
I've wrote sample for you:
int N = 10, M = 15;
NSMutableArray *ints = [NSMutableArray arrayWithCapacity:N]; // array[N][M]
for (int i=0; i<N; i++)
{
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:M];
for (int j=0; j<M; j++)
{
[arr addObject:[NSNumber numberWithInt:(i+1)*(j+1)]];
}
[ints addObject:arr];
}
// print
for (int i=0; i<[ints count]; i++)
{
NSString *line = #"";
NSMutableArray *arr = [ints objectAtIndex:i];
for (int j=0; j<[arr count]; j++)
line = [NSString stringWithFormat:#"%# %#", line, [arr objectAtIndex:j]];
NSLog(#"%#", line);
}
If you want to dynamically allocate memory, in other words define the size of the arrays at runtime, then you need to declare the array as a pointer, malloc it, and then add another array of ints to each index at runtime. You can't really declare and dynamically allocate at the class level. If you are using cocoa/iphone sdk you can use NSMutableArray.
You could also create your own class that constructs a two dimensional array and exposes methods to push and pop int objects like [IntegerArray push:x,y,n];
Here's and example of using a double reference as Daniel R Hicks pointed out.
I'm trying to convert a sectionned table into a flat list using this function into didSelectRowAtIndexPath (I have a NSArray that is initialisated with the number of items contained in each section) :
Somewhere... :-)
self.sectionsArray = [NSArray arrayWithObjects:macroIntNumber(1), macroIntNumber(3), macroIntNumber(12), nil];
then into didSelectRowAtIndexPath :
int selectedRow = 0;
int a = indexPath.section;
for (int i=0; i<indexPath.section-1; i++) {
selectedRow += [[self.sectionsArray objectAtIndex:i] intValue];
}
selectedRow += indexPath.row;
But... This crashes for indexPath.section = 0 (first section).
Because the loop is played infinitly until crash of the NSArray call...
Strange !!!
forcing for (int i=0; i<0-1; i++) { works
forcing for (int i=0; i<a-1; i++) { works
What am I missing ?
section is an NSUInteger, so it's unsigned. Thus, subtracting 1 from 0 on that unsigned integer is taking you to a very large number rather than -1.
It works when using a, because you've declared a as an int. :)