NSInteger to NSArray iPhone - iphone

I have NSInteger variable, for example NSInteger example=1256 and i need an array with elements of this variable.
so first element of array is array[0] = 1
array[1] = 2
array[2] = 5 etc..
what way can i solve it ?

Here's about how I'd do it:
NSUInteger number = 1234567890;
NSMutableArray * numbers = [NSMutableArray array];
while (number > 0) {
NSUInteger lastDigit = number % 10;
[numbers insertObject:[NSNumber numberWithUnsignedInteger:lastDigit] atIndex:0];
number = number / 10;
}

You need to use NSMutableArray to be able to change entries. NSMutableArray can only hold objects, not primitive types like NSInteger. Also, if you are using NSMutableArray, you can't access the elements the same way as with a C array.
[array insertObject:[NSNumber numberWithInteger:2] atIndex:1];

You can convert your integer to a char* then iterate through it casting each character back to an int and adding it to a C array or, as Steven says, an NSArray of NSNumbers.

Related

Using a for-in loop with NSInteger?

I have an NSMutableArray populated with NSIntegers. I need to loop through the array. I could do:
// given NSMutableArray *array of NSIntegers
NSUInteger n = [array count];
for (NSInteger i = 0; i < n; i++) {
NSInteger x = [array objectAtIndex:i];
// query SQLite WHERE id = x
}
However, it seems that a for (object in array) loop would be cleaner. iOS 5 does not accept NSIntegers or NSNumbers as objects in for-in loops. Should I loop through the array with NSObjects, casting the NSObject to an NSInteger during each iteration? Is there another way? Or is a for loop like the one above the cleanest solution to this problem?
In Objective-C you can use a for-in loop with NSNumber like this:
NSArray *array = /*NSArray with NSNumber*/;
for (NSNumber *n in array) {
NSLog(#"i: %d", [n intValue]);
}
Check this out.
Mostly, you will not be allowed to have an NSMutableArray of NSUInteger (aka unsigned long) as it's not an objective-c object.
You may use the c style.
NSUInteger array[] = {value1,value2,value3};
int size = sizeof(array)/sizeof(array[0]);
for (int i=0; i<size; i++) {
NSInteger value = array[i];
// do whatever you want
}

NSMutable Array beyond bounds

I have a block of code which when executed gives me this error. And I am relatively new, I can't seem to fix the problem.
Error:
2011-09-06 12:31:06.094 ForceGauge[266:707] CoreAnimation: ignoring exception: * -[NSMutableArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]
-(void)peakCollector:(NSMutableArray *)testarray {
NSUInteger totalRows = [testarray count];
NSMutableArray *percentArray = [[NSMutableArray alloc]initWithObjects:0, nil];
if(forcecontroller.selectedSegmentIndex==0)
testarray = lbData;
else if(forcecontroller.selectedSegmentIndex==1)
testarray = kgData;
else if(forcecontroller.selectedSegmentIndex ==2)
testarray = ozData;
else if(forcecontroller.selectedSegmentIndex ==3)
testarray = newtonData;
for(int i = 0; i< totalRows-1; i++) {
if ([[testarray objectAtIndex:i+1] doubleValue] >= 1.2 * [[testarray objectAtIndex:i] doubleValue]) {
percentArray = [testarray objectAtIndex:i];
DatabaseTable *tableVC = [[DatabaseTable alloc] initWithStyle:UITableViewStylePlain];
[self.navigationController pushViewController:tableVC animated:YES];
if(forcecontroller.selectedSegmentIndex==0)
[tableVC copydatabase:percentArray];
else if(forcecontroller.selectedSegmentIndex==1)
[tableVC copydatabase:kgData];
else if(forcecontroller.selectedSegmentIndex==2)
[tableVC copydatabase:ozData];
else if(forcecontroller.selectedSegmentIndex==3)
[tableVC copydatabase:newtonData];
[tableVC release];
} else {
[analogData removeAllObjects];
}
}
}
There are multiple issues here:
1) NSArrays can only contains NSObjects.
In your code, you are initializing your NSArray using [[NSMutableArray alloc]initWithObjects:0, nil];, but 0 is an atomic type, not an NSObject
(and basically 0 is the same value as nil (nil and NULL are typically equal to 0, interpreted as the id and void* types, respectively)
You have to encapsulate your 0 value in an NSNumber instead :
[[NSMutableArray alloc]initWithObjects:[NSNumber numberWithInt:0], nil];
Then retrieve the NSNumber using [percentArray objectAtIndex:0] and finally convert back the retrieve NSNumber to int using NSNumber's intValue method:
NSNumber* number = [percentArray objectAtIndex:0]; // returns an NSNumber which is an NSObject encapsulating numbers, see Apple's documentation
int val = [number intValue]; // retrieve the integer value encapsulated in the NSNumber
// or directly:
// int val = [[percentArray objectAtIndex:0] intValue];
2) The exception you got is in fact elsewhere and is much more subtle: you are retrieving the [testarray count] value in an NSUInteger variable, which is an unsigned type. Then totalRows-1 will do some tricky things if totalRows is equal to 0 (which is obviously the case considering the exception you have).
As totalRows is an NSUInteger, when it is equal to 0, totalRows-1 will not be equal to -1, but to... (NSUInteger)-1 (-1 interpreted as an unsigned integer), which is 0xFFFFFFFF, or namely the maximum value of the NSUInteger type!
This is why i is always less than this totalRows-1 value (as this value is not -1 but 0xFFFFFFFF = NSUInteger_MAX).
To solve this issue, cast your totalRows variable to an NSInteger value, or add a condition in your code to treat this special case separately.
Please check the how many objects test array contains at beginning of for loop.
Other thing that can help is that avoid NSUInteger and use simple int for storing array count.
Please post if this don't work.
The error simply means that you're trying to retrieve an object at an index that does not exist. In your specific case, the array you're trying to get the object from does not have an object at index 1
An easy example
[0] => MyCoolObject
[1] => MySecondObject
[2] => ObjectTheThird
You can access indexes 0,1,2 of your array as they contain objects. If you now would try to access index 3 it would throw the Out of bounds exception as index 3 does not exist.

How to store integer value into an NSMutableArray in iphone

I have NSMutableArray having values 10,15,26,28. I want to store them into another array as an integer form how do i store them.
Thanks :)
here how to add
[array addObject:[NSNumber numberWithInt:10]];
you can get the integer value like
//assuming array has nsnumber/nsstring objects.
[[array objectAtIndex:index] intValue];
Here's an example of how to do this:
int yourInt = 5;
[myMutableArray addObject:[NSNumber numberWithInt:yourInt]];
You can't store C types in a NSMutableArray, you can only store objects.
Create NSNumber's from your int values with [NSNumber numberWithInteger:10];...
You can then get the int value back with [aNSNumberObject intValue];
If you want to store integers in an array it has to be a C array:
#define C_ARRAY_MAX_SIZE 10
int cTab[C_ARRAY_MAX_SIZE];
int i=0;
for (NSNumber* n in yourMutableArray) {
cTab[i] = [n intValue];
i++;
}

Gather the count of a specific object from NSMutableArray

Hey guys & girls,
Im wondering how I can find the object count of a specific type of object in an array.
For example, i have 6 'clouds' in NSMutableArray at random locations, I also have 4 'dragons' in this NSMutableArray.
How can i gather the integer 6?
I was thinking something along the lines of:
int z = [[SomeClass *clouds in _somearray] count];
Any assistance would be greatly appreciated.
Thnx,
Oliver.
Yet another way is in using blocks:
Class cloadClass = NSClassFromString(#"Cloud");
NSArray *a = /* you array with clouds and dragons */;
NSIndexSet *clouds = [a indexesOfObjectsPassingTest:
^(id obj, NSUInteger idx, BOOL *stop) {
return [obj isKindOfClass:cloadClass];
}];
// now we can count clouds
NSLog(#"%d", [clouds count]);
// but also we now can return our clouds immediately and
NSLog(#"%#", [a objectsAtIndexes:clouds]);
int result = 0;
for (NSObject *object in _somearray) {
if ([object isKindOfClass:[SomeClass class]])
result++;
}
result is the count you are looking for
If you're looking for how many times a specific instance of an object appears, you can do:
NSCountedSet *counts = [NSCountedSet setWithArray:myArrayOfObjects];
NSUInteger count = [counts countForObject:myObject];
Otherwise you'd just have to loop through the array manually and count.

float* array to NSArray, iOS

I have a float pointer array and I would like to convert it to an NSArray.
Is there a better way to do it than to iterate through the float* and add each entry to the NSArray?
I have:
float* data = new float[elements];
fill up data from binary ifstream
I want to avoid doing something like:
NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:elements];
for (int i=0;i<elements;i++)
{
[mutableArray addObject:[NSNumber numberWithFloat:data[i]]];
}
NSArray *array = [NSArray arrayWithArray:array];
Is there some convenience / more efficient method to copy a large chunk of floats into an NSArray?
Regards,
Owen
You’ve got two problems: first, you can’t store a float in an NSArray, since NSArrays will only hold Objective-C objects. You’ll need to wrap then in an object, probably NSNumber or NSValue.
As to your original question, since you have to create the objects anyway, there isn’t a better method. I’d recommend the for loop:
for (int i = 0; i < elements; i++) {
NSNumber *number = [NSNumber numberWithFloat:floatArray[i]];
[myArray addObject:number];
}
Keep in mind that number will be autoreleased. If you’re dealing with a lot of numbers, that can get out of hand pretty quickly with memory management, so you might do this instead:
for (int i = 0; i < elements; i++) {
NSNumber *number = [[NSNumber alloc] initWithFloat:floatArray[i]];
[myArray addObject:number];
[number release];
}