Error with using local variable to access array index - objective-c

For some reason this occurs every time i try to access a specific index from the array by specifying a variable int in the index in a forloop. When i do i get a Thread 1 Error, but if i use a variable that has not be declared in the forloop itself than it seem to work fine.
Code:
for(int i =0 ; i<= [array count]; i++) {
NSNumber *convert = [array objectAtIndex:i]; //results in error
NSLog(#"%i", [convert intValue]);
}

Problem is you are trying to access array beyond its capacity. Array starts with 0 index and goes upto array.count - 1. That said, please try with below code and you should be good:
for (int i = 0 ; i <= array.count - 1 ; i++) {
NSNumber *convert = [array objectAtIndex:i];
NSLog(#"%i", [convert intValue]);
}
Another variation could be:
for (int i = 0 ; i < array.count ; i++) {
NSNumber *convert = [array objectAtIndex:i];
NSLog(#"%i", [convert intValue]);
}

Related

Initialize NSArray with size

How do I initialize an NSArray with size only so to use a for loop to fill it later? My for loop would be
for (int i = 0; i < [myArray count]; i++) {
myArray[i] = someData;
}
You don't need to initialize it with a specific size - you can add objects later:
NSMutableArray *myArray = [NSMutableArray array];
for (int i = 0; i < 100; i++) {
[myArray addObject:someData];
}
There are slight performance gains if you know the size ahead of time:
NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:100];
But this is optional.
NSNull is the class used to represent an unset, invalid or non-existent object. Therefore you can pad the array to a specific size using instances of this class.
NSUInteger sizeOfArray = 10;
NSMutableArray *someArray = [NSMutableArray array];
for (NSUInteger i = 0; i < sizeOfArray; i++) {
[someArray addObject:[NSNull null]];
}
Further, you can't use the syntax someArray[i] = xyz; if the value at position i doesn't exist, as it will cause an out of bounds error.

How to send values to Ivar in method

new to Objective-C and keeping it very very simple I'm looking to understand one thing at a time... I set up a very simple class called student all it does is add two numbers trying to see how things pass into and back from methods) **I rewrote the code ==>> look at end to see the version that works **
If I have a method that has
#property (nonatomic) int firstNum;
#property (nonatomic) int secondNum;
and I have an instance of my class called student I assign a value to firstNum like student.firstNum = 100; student.secondNum = 77; that is easy and the method adds them and sends the sum in a return
But in main I tried assigning it from an array and it did not work I tried
student.firstNum = [myIntegers objectAtIndex:0];
and
student.firstNum = [myIntegers objectAtIndex:i]; //using a for loop with i index
it says incompatible pointer to integer conversion
Here is the snippet from main I tried it's not complete it just is trying to set firstNum eventually I will also set up secondNum and send each pair to the method to get added together but for now I am stuck trying to get the firstNum assigned the value in myIntegers[i] to start
NSMutableArray *myIntegers = [NSMutableArray array];
for (NSInteger i= 0; i <= 10; i++) {
[myIntegers addObject:[NSNumber numberWithInteger:i]]; // this works up to here
student.firstNum = [myIntegers objectAtIndex:i]; // this does not work
}
I also tried [i].
Here is my method:
- (int)addNumbers {
int sum = self.firstNum + self.secondNum;
return sum;
}
HERE IS WHAT WORKS : assuming I have a student object
.m
(long)addNumbers:(NSNumber *)x :(NSNumber *)y {
long sum;
sum = [x integerValue] + [y integerValue];
return sum;
}
main
NSMutableArray *myIntegers1 = [NSMutableArray array];
NSMutableArray *myIntegers2 = [NSMutableArray array];
for (NSInteger i= 0; i <40; i++) {
[myIntegers1 addObject:[NSNumber numberWithInteger:i]];
[myIntegers2 addObject:[NSNumber numberWithInteger:i]];
long sum = [student addNumbers:[myIntegers1 objectAtIndex:i] :[myIntegers2 objectAtIndex:i]];
NSLog(#" The sum is %ld", sum);
}
You are creating a properties of type int, but in your for loop, you are trying to assign them an NSNumber.
NSNumber is a simple container for a c data item and can hold int, float, char, bool, etc.
Change your loop to be like that:
for (NSInteger i= 0; i <= 10; i++) {
[myIntegers addObject:[NSNumber numberWithInteger:i]];
student.firstNum = [[myIntegers objectAtIndex:i] intValue]; // this 'extracts' the int value from the NSNumber
}

NSArray not removing objects

I have 5 objects in Array and want to delete 2 in loop but I have a small minor problem in below code
NSMutableArray *totalPages = [[NSMutableArray alloc] init];
[totalPages addObject:#"Test1"];
[totalPages addObject:#"Test2"];
[totalPages addObject:#"Test3"];
[totalPages addObject:#"Test4"];
[totalPages addObject:#"Test5"];
int currentPage = 2;
for (int x = 0; x < [totalPages count]; x++) {
//int pageIds = [[totalPages objectAtIndex:x] intValue];
//NSLog(#"%d",pageIds);
NSLog(#"Array Count %d", (int)[totalPages count]);
NSLog(#"Current Page %d", currentPage);
NSLog(#"Current Iterator Value %d", x);
if (x > currentPage) {
[totalPages removeObjectAtIndex:x];
NSLog(#"Array Count %d", (int)[totalPages count]);
NSLog(#"Number of Pages to be removed %d", x);
}
}
As I want to delete "Test4" and "Test5" but my above code is deleting only "Test5" and if I keep this logic as
if (x >= currentPage)
so it deletes my "Test4" and "Test5" objects but logic fails when int currentPage = 0; so what is the recommended approach to delete Test4 and Test5 as objects in arrays are dynamically added and when currentPage = 0; so Arrays has only 1 Object in it as a pages.
The array is changing as you deleting elements from it, it is getting shortened.
Adjust your for statement and count backwards, that should solve the problem for you.

Iterating backwards over an array throwing exception

I am trying to make an add method that works like long addition, so I want to start the addition from the end and work my way backwards so I can get the carrys right and etc. So I am currently trying to start working backwards over the array.
For example what im trying to do.
two arrays with the character 123456789
and i want to add them starting at 9 + 9 then move to 8+8
So I'm pretty sure I'm using the right way to iterate backwards over an array, but everytime I try I get just the runtime error, index out of bounds, and I can't figure out why. Any help would be great, I just cant figure out why it keeps throwing the exception.
-(MPInteger *) add: (MPInteger *) x
{
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
//for (int i = 0; i < [a count]; i++) {
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *ourNum = [NSNumber numberWithInt:num];
NSNumber *total = [NSNumber numberWithInt:[[a objectAtIndex:i] intValue] + [[b objectAtIndex:i] intValue]];
if ([total intValue] >= [ourNum intValue]) {
total = [NSNumber numberWithInt:([total intValue] - [ourNum intValue])];
[c addObject:[NSNumber numberWithInt:([total intValue])]];
} else {
[c addObject:[NSNumber numberWithInt:[[a objectAtIndex:i] intValue]+[[b objectAtIndex:i] intValue]]];
}
NSLog(#"%#", c[i]);
}
return x;
}
First, let's clean up this code.
- (MPInteger *)add:(MPInteger *)x {
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *ourNum = #(num);
NSNumber *total = #([a[i] intValue] + [b[i] intValue]);
if ([total intValue] >= [ourNum intValue]) {
total = #([total intValue] - [ourNum intValue]);
[c addObject:#([total intValue])];
} else {
[c addObject:#([a[i] intValue] + [b[i] intValue])];
}
NSLog(#"%#", c[i]);
}
return x;
}
Next, let's remove redundant/duplicate code.
- (MPInteger *)add:(MPInteger *)x {
NSMutableArray *a = self->intString;
NSMutableArray *b = x->intString;
NSMutableArray *c = [NSMutableArray arrayWithCapacity:100];
for (NSInteger i = [a count] - 1; i > 0; i--) {
int num = 10;
NSNumber *total = #([a[i] intValue] + [b[i] intValue]);
if ([total intValue] >= num) {
total = #([total intValue] - num);
}
[c addObject:total];
NSLog(#"%#", c[i]);
}
return x;
}
Now we can clearly see all of the issues.
You're going from [a count] - 1 to 1. You should be going all the way to 0.
a and b might have different sizes, so if you only do [a count] - 1 to 0, then if for example [b count] < [a count], you'll get an index out of bounds error when you try to access b[i].
You're adding stuff to the end of c, but you should be adding it to the beginning of c since you're iterating backwards.
You don't store the carry anywhere.
You are accessing c[i], which doesn't exist.
You are starting with an empty array 'c', and you NSLog c[i] which is obviously out of bounds on the first iteration.

Array - find how many times an object repeats consecutively

My array objects are as follows:
10,10,10
20,23,14
10,10,10
10,10,10
10,10,10
32,23,42
32,23,42
10,10,10
32,23,23
32,23,23
How can I go through this array and find out how many times the same object repeats sequentially, then add a , and the number of times it repeats?
Then save a new array with objects like:
10,10,10,1
20,23,14,1
10,10,10,3
32,23,42,2
10,10,10,1
32,23,23,2
Any help would be appreciated.
Thanks!
Try this:
NSMutableArray *outArray = [[NSMutableArray alloc] init];
for (NSUInteger j = 0; j < [theArray count]; j++) {
id object = [theArray objectAtIndex:j];
NSUInteger repeats = 1;
while (j + 1 < [theArray count] && [[theArray objectAtIndex:j + 1] isEqual:object]) {
j++;
repeats++;
}
[outArray addObject:object];
[outArray addObject:[NSNumber numberWithUnsignedInteger:repeats]];
}
return outArray;
This can also be done in place if the input array is mutable. I leave that as an exercise for the reader.
Break up every three integers into its own array (make sure they are strings).
Then iterate through each one of those arrays, and input into an NSMutableDictionary, the key is the string (your number), the value is a counter (if seen once, add 1, etc...)
Keep a pointer to the highest key (if newCount > highestCountPointer, then highestCountPointer=newCount)
At the end of that iteration, add the number that the highestCountPoints to to the end of the array.
I'm not an Objective C programmer, so please pardon any language gaffes. Something like the following should do the job:
NSMutableArray *result = [[NSMutableArray alloc] init];
id pending = nil;
NSUInteger count = 0;
for (NSUInteger i = 0; i < [theArray count]; i++) {
id object = [theArray objectAtIndex:i];
if ([object isEqual:pending]) {
count++;
} else {
if (pending != nil) {
[result addObject:[NSString stringWithFormat:#"%#,%d", pending, count]];
}
pending = object;
count = 1;
}
}
if (pending != nil) {
[result addObject:[NSString stringWithFormat:#"%#,%d", pending, count]];
}
Just run "uniq -c" from command line :)