float [] array problem in objective c - objective-c

I am coding in xcode by objective c. I came up with a problem.
I want to try like
declare float[] weights;
results looks like this
weight[0] = 0.5
weight[1] = 0.4
weight[2] = 0.9
A.h
NSMutableArray *weight;
A.m
weights = [NSMutableArray array];
for(int i=0; i < 4; i++) {
float randomNumber = arc4random() % 11;
[weights addObject:[[NSNumber alloc] initWithFloat:randomNumber]];
NSLog(#" for loops color prob weghts=%f",[weights objectAtIndex:i] );
}
I don't know what is wrong with this code. Please help me to find out?
When I print it by NSLOG " all [weight = 0.000] and also How do I access like [weight floatvalue].
secondly, when I create this class to another class there are weight [0],[1],[2],[3] and no values

It should be [[weights objectAtIndex:i] floatValue] when you print it in your NSLog

NSNumber is a class, not a integral type.
Therefore, you must use %#, not %f.
NSLog(#" for loops color prob weghts=%#",[weights objectAtIndex:i] );
Alternatively, use floatValue, like you said. You may need to cast the object into NSNumber first (for type safety)
NSNumber *number = (NSNumber *)[weights objectAtIndex:i];
NSLog(#" for loops color prob weghts=%f", [number floatValue]);
Also, you are leaking objects here, because you did not release them after putting them in the array. Either release after placing them in array, or use [NSNumber numberWithFloat:]

Related

Get numeric value without error "Subscript requires size of interface 'NSArray', which is not constant in non-stable ABI"

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...

Using many integers in Objective-C

I'm new to programming, I have some basic python programming from college, I am familiar with some of the OOP basics and would like some help with managing large amounts of integers. I have 88 of them. 7 will be used for capturing user input and the other 81 will be used for a specific calculation. Instead of writing the following code:
int currentPlace;
int futurePlace;
int speed;
int distance;
int place1 = 1;
int place2 = 2;
int place3 = 3;
// etc...
int place81 = 81;
And then later coming back to the integers and asking user defined questions such as:
NSLog(#"What place is the runner in?");
scanf("%i", &currentPlace);
NSLog(#"What place does the runner finish in?");
scanf("%i", &futurePlace);
NSLog(#"What is the distance of the track?");
// doing some math
NSLog(#"The runner is running at "i" MPH.",speed);
I remember there being an easier way to use the integers but I keep thinking enums or typedefs.
I'd like for the user to pick a number and not have to run a huge if statement to get the work done to cut the size of the program as much as possible.
This is my first "on my own" application so any helpful pointers would be great.
Thanks.
I haven't understood why you need all these place's, but I also assume that an array would be easier to use here. You can use either NSArray or NSMutableArray. The difference between them is that an NSArray instance can't be changed after being created (you can't add/remove elements) unlike an NSMutableArray.
Using NSArray
NSArray *places = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2],[NSNumber numberWithInt:3], ..., [NSNumber numberWithInt:81], nil];
nil at the end means the end of the contents of an array. [NSNumber numberWithInt:1] returns an int given as an argument (we can't straight give an int to the array, as an array expects an object as an argument.
You can access the contents of the array using:
[places objectAtIndex:(NSUInteger)];
Remeber that an array starts counting with 0, so if you want to get 5, you have to do this
[places objectAtIndex:4];
Using NSMutableArray
I suggest that you should use this option.
It's easier to use for here.
NSMutableArray *places = [NSMutableArray array];
for (int i = 1; i < 81; i++)
{
[places addObject:[NSNumber numberWithInt:i]];
}
Then you can access data the same way as in the NSArray:
[places objectAtIndex:0];
This will return 1. You can start the for-cycle with 0. After that the index of an array will correspond to the integer inside, so
[places objectAtIndex:5];
will actually return 5.
Are you thinking of a C array?
int myPlaces[81];
for (int i=0; i<81; i++) {
myPlaces[i] = 0;
}

Creating a C Array from 2D NSArray

I have a 2D NSArray of string numbers that I would like to convert to a 2D C array of doubles for use with BLAS/LAPACK functions (through the accelerate framework).
This line of code seems to work, however seems to be incredibly inefficient and eventually crashes due to a malloc error. Is there a more efficient way to convert this 2D NSArray to a C array? Or a convienent way of using NSArrays with BLAS/LAPACK?
double gridDataC[[nrows intValue]+1][[ncol intValue]+1];
for(i=6;i<[fileLines count]-1;i++){
for(j=0;j<[ncol intValue]-1;j++){
gridDataC[i][j]=[[[[fileLines objectAtIndex:i] componentsSeparatedByString:#" "] objectAtIndex:j] doubleValue];
}
}
fileLines is an array that contains lines of a file that are parsed into respective numbers.
There are few things here that deal with memory.
1.componentsSeparatedByString: creates an autoreleased array. Since you're looping for every object within that string, you are creating similar array multiple times. As the autoreleased objects are not released until the end of the runloop this might clog the memory. It's better to do this once by bringing the method call out of the inner loop.
2.The value of i is the most confusing. You pass i as the index for gridDataC. It should probably be i - 6 if you're starting from i = 6.
double gridDataC[[nrows intValue] + 1][[ncol intValue] + 1];
for( i = 6; i < [fileLines count] - 1; i++ ){
NSArray * components = [[fileLines objectAtIndex:i] componentsSeparatedByString:#" "];
for( j = 0; j < [ncol intValue] - 1; j++ ){
gridDataC[i - 6][j] = [[components objectAtIndex:j] doubleValue];
}
}

Passing NSArray to a cpp function

I need to call a cpp function like
void myFunc(float **array2D, int rows, int cols)
{
}
within an objective-c object. Basically, the array is created in my objective-c code as I create an NSArray object. Now, the problem is how to pass this array to my cpp function.
I am a bit new to these mixed c++/objective-c stuffs so any hint will be highly appreciated.
Thanks
I guess you have to convert the NSArray to a plain C array.
Something like:
NSArray *myNSArray; // your NSArray
int count = [myNSArray count];
float *array = new float[count];
for(int i=0; i<count; i++) {
array[i] = [[myNSArray objectAtIndex:i] floatValue];
}
or, as a commenter suggested (assuming your NSArray contains NSNumbers):
NSArray *myNSArray; // your NSArray
int count = [myNSArray count];
float *array = new float[count];
int i = 0;
for(NSNumber *number in myNSArray) {
array[i++] = [number floatValue];
}
Look at this post.
Check out the answer that mentions using [NSArray getObjects] to create a c-style array.
Here's the code that the poster put in there:
NSArray *someArray = /* .... */;
NSRange copyRange = NSMakeRange(0, [someArray count]);
id *cArray = malloc(sizeof(id *) * copyRange.length);
[someArray getObjects:cArray range:copyRange];
/* use cArray somewhere */
free(cArray);
Alternately, since CFArray is toll-free bridged to NSArray, could you call those C functions from your C++ function? I'd look around, wouldn't be surprised if there weren't a C++ wrapper to give similar semantics, or one could be written easily enough.

Multidimensional arrays - what's the most convenient way to work with them in Objective-C?

I'm a beginner in Objective-C and I'm trying to find the most convenient way to work with multidimensional arrays in Objective-C. Either I am missing something or they are very ugly to work with.
Let's say we have a classic problem:
read input from file; on the first line, separated by space(" ") are the width and height of the matrix (eg: 3 4)
on the following lines there is the content described by the values above
Eg:
3 4
a b c d
e f g h
i j k l
The first solution I thought of was:
NSMutableArray *matrix = [[NSMutableArray alloc] initWithCapacity: x]; //x = 3 in this specific case
NSMutableArray *cell;
for(cell in matrix)
{
cell = [NSMutableArray initWithCapacity: y];
for(int i = 0; i < y; i++) // y = 4
{
//object is a NSString containing the char[i][j] read from the file
[cell insertObject:object atIndex: i];
}
}
This was the first thing I had in mind when thinking about how I should get my values read from file in a multidimensional array. I know you can use C arrays, but since I will store NSObjects in it, I don't think is such a great idea. Nonetheless, from my point of view is easy to work with C arrays rather the solution I got with Objective-C.
Is there another way you could build a multidimensional array in obj-c and easier than the one above?
How about looping them?
I know I can do something like
NSArray *myArray;
for(int i=0; i < [array count]; i++)
{
[myArray arrayWithArray: [array objectAtIndex: i]];
for(int j=0; j < [myArray count]; j++)
{
NSLog(#"array cell [%d,%d]: %s", i, i, [myArray objectAtIndex: j]);
}
}
But that is still more complicated than your average C multidimensional array loop.
Any thoughts on this?
Objective-C is a superset of C, if you want to work with multidimensional arrays like you would in C, do it that way. If you want to work with objects doing it the Cocoa way, then that's fine too, but you will write more code to do it.
Can you not simply make an array of id?
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
id ptr[3][4];
NSObject *p;
ptr[0][0] = p;
}
You can do nothing more with NSArray or NSMutableArray in this regard. That is there is nothing like objectAtIndex:i :j
You can always create one-dimensional arrays of the size width * height instead:
const int size = width*height;
NSMutableArray *array = [NSMutableArray arrayWithCapacity:size];
for (int i=0; i<size; ++i) {
NSString *string = [NSString stringWithFormat:#"col=%d, row=%d", i%width, i/width];
[array insertObject:string atIndex:i];
}
Nobody uses direct multi-dimensional arrays of any size in any computer language (except for homework). They simply use too much memory and are therefore too slow. Objective-C is an object-oriented language. Build a class that does what you need.