Store/Retrieve values from Objective-C++ to Objective-C - iphone

How can I store an Objective-C++ short int like the one below in an Objective-C array and convert it back to Objective-C++ later? I've attempted the following with no success. Any help would be great!
short int *tmpbuffer = ( short int*)malloc(sizeof(short int)*length*inData);
int count = 0;
for (count = 0; count < length*inData; count++)
{
tmpbuffer[count] = (short int) (inbuffer[count] * 0x7fff);
}
size = fwrite(tmpbuffer, 1, sizeof(short int)*length*inData,fp);
[fwriteSections addObject:[NSNumber numberWithShort:tmpbuffer]];
[fwriteSections addObject:[NSNumber numberWithShort:sizeof(short int)*length*inchannels]];
[fwriteRows addObject:fwriteSections];

There is no need to do any conversion between Objective C++ and Objective C for a simple byte buffer. You can just pass a short int pointer between Objective C++ and Objective C classes.
If you mean, how can you convert a short int byte buffer to an NSArray, then you are on the right track, just do the following:
short int *buffer = malloc(size * sizeof(short int));
NSMutableArray *shortArray = [NSMutableArray arrayWithCapacity:size];
for (NSUInteger i = 0; i < size; i++) {
[shortArray addObject:[NSNumber numberWithShort:buffer[i]]];
}
I would not recommend this approach though, it is not efficient, you are better off just sticking with the C style buffer.

Related

Divide NSInteger with int

I am trying to divide NSInteger with some number, but I am receiving errors.
This is what I am trying to do:
length = [corner count];
for (int i=0; i<length; i++) {
if ([resultDate rangeOfString:[corner objectAtIndex:i]].location != NSNotFound) {
cornerResult++;
}
}
cornerResultLabel.text = [NSString stringWithFormat:#"%i", cornerResult];
This works as it should.. I search through the array and count the results and write it.
But, I need cornerResult divided with 4. When I add cornerResult / 4 it shows me the error(as I wrote in comment). I have no idea why is this making problem.
you probably meant to divide the intValue of the NSNumber, not the NSNumber* itself:
int num = number.intValue;
int result = num / 4;
(full code sample and error message would help)
You are dividing an int which becomes a float , use %f instead.
I fix it this way. First I defined int and after that I set NSInteger value to int and after that divide.
int helper = cornerResult;
helper = helper / 4;

Confusing arrays

Kinda new to iOS, Im also studying Android. kinda confuse on arrays.
How to convert this into iOS:
result as being the index
nextresult[x] array of indexes
for(x = 0; x < array.size; x++)
{
if(result < nextresult[x])
nextresult[x] -= 1;
}
It will iccheck all of the content of the arrays if it needs to be adjusted or not,
Might be following will give you some idea -
As you mentioned, i have considered following - result' is value andnextresult` is array.
for(x = 0; x < [array count]; x++)
{
if(result < [nextresult objectAtIndex:x]) {
[nextresult objectAtIndex:x] -= 1;
}
}
EDIT -
if you want to add integer in arrays -
[yourArray addObject:[NSNumber numberWithInt:1]]; // Objective C array store objects. so we need to convert primitive data type into object.
Read Apple's excellent developer documentation.
You can find the docs about the NSArray class here, or in your Xcode organizer.
I have downvoted your question, because it could very easily have been solved by just looking at the docs.

Objective-C += equivalent?

Sorry for the newbie question, but i cannot find an answer to it.
I have a simple operation. I declare a variable, and then i want to loop through an array of integers and add these to the variable. However, i can't seem to find how to get a += equivalent going in Objective C.
Any help would be awesome.
Code:
NSInteger * result;
for (NSInteger * hour in totalhours)
{
result += hour;
}
NSInteger is not a class, it's a typedef for int. You cannot put it into collections like NSArray directly.
You need to wrap your basic data types (int, char, BOOL, NSInteger (which expands to int)) into NSNumber objects to put them into collections.
NSInteger does work with +=, keep in mind that your code uses pointers to them, which is probably not what you want anyway here.
So
NSInteger a = 1, b = 2;
a += b;
would work.
If you put them with [NSNumber numberWitInt:a]; etc. into an NSArray, this is not that easy and you need to use -intValue methods to extract their values first.
If totalhours actually contains NSNumber objects you need the following:
NSInteger result = 0;
for(NSNumber* n in totalhours)
{
result += [n integerValue];
}
The problem is that you are confusing NSInteger (a typedef for int or long) with a class instance such as NSNumber.
If your totalhours object is an array of NSNumber objects, you'll need to do:
NSInteger result;
for (NSNumber *hour in totalhours)
{
result += [hour integerValue];
}
No problem using the '+=' operator, just be sure about the objects you are working with...
Your code might be :
NSNumber *n; NSUInteger t = 0;
for(n in totalHours) {
t += [n integerValue];
}
// you got your total in t...
The += operation definitly works. All you need to do is initialize your result variable so it has a start value.
E.g. NSInteger * result = 0;
Good luck!
Your problem is probably that you're using a pointer to an NSInteger instead of an actual NSInteger. You're also not initializing it. Try this:
NSInteger result = 0;
for (NSInteger * hour in totalhours)
{
result += *hour;
}

three integers compare

I have three integers
I would like to determine what is the highest and which is the lowest value using Objective-C
Thank you!
It is good to store that numbers in an array. Just plain C array is good enough and in Objective-C best for performance. To find a minimum you can use this function. Similar for maximum.
int find_min(int numbers[], int N){
int min = numbers[0];
for(int i=1;i<N;i++)
if(min>numbers[i])min=numbers[i];
return min;
}
If that is just three numbers you can do the comparisons manually for best performance. There is a MIN() and MAX() macro in Cocoa in Foundation/NSObjCRuntime.h. For the maximum, just do:
int m = MAX(myI1, MAX(myI2, myI3));
This may be scaled to more numbers and may be faster than the first approach using loop.
Unfortunately there is no short and elegant neither a generalized way for that in Cocoa.
Plain C Array + custom loop would be the best. With an NSArray you would have to wrap the Integers in NSNumbers without getting any benefit out of that.
Objective-C's built in MAX(a,b) and MIN(a,b) macros only work for two values.
I have two macros I've created for using 2 or more values called multi-max and multi-min (MMAX and MMIN)
Here is their definition, just copy paste into your .h
#define MMAX(...) ({\
long double __inputs[(sizeof((long double[]){__VA_ARGS__})/sizeof(long double))] = {__VA_ARGS__};\
long double __maxValue = __inputs[0];\
for (int __i = 0; __i < (sizeof((long double[]){__VA_ARGS__})/sizeof(long double)); ++__i) {\
long double __inputValue = __inputs[__i];\
__maxValue = __maxValue>__inputValue?__maxValue:__inputValue;\
}\
__maxValue;\
})
#define MMIN(...) ({\
long double __inputs[(sizeof((long double[]){__VA_ARGS__})/sizeof(long double))] = {__VA_ARGS__};\
long double __minValue = __inputs[0];\
for (int __i = 0; __i < (sizeof((long double[]){__VA_ARGS__})/sizeof(long double)); ++__i) {\
long double __inputValue = __inputs[__i];\
__minValue = __minValue<__inputValue?__minValue:__inputValue;\
}\
__minValue;\
})
Example use:
x = MMAX(2,3,9,5);
//sets x to 9.

Using a C function in Objective-C (for iPhone)

'lo all. I am a self-described admitted noob in iPhone programming (having a much longer perl & web background -- 30 years)...but took the plunge last week and bought a couple of good books. After cramming and reading well over 1000 pages -- and understanding it pretty well, I am well on my way to a good first Native iPhone app. My problem is this: I do not know how to do a simple Geographic (lat/long) point-in-polygon routine in Objective-C. I have 2 ways of doing this. One in C (the first code example) and one in JavaScript (the second code example):
// this is the poly.h file
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy);
// this is the poly.c file
#include "poly.h"
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy){
int i, j, c = 0;
for (i = 0, j = nvert-1; i < nvert; j = i++) {
if ( ((verty[i]>testy) != (verty[j]>testy)) &&
(testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
c = !c;
}
return c;
}
or this (in Javascript):
function _isPointInPoly(poly, pt){
for(var c = false, i = -1, l = poly.length, j = l - 1; ++i < l; j = i)
((poly[i].y <= pt.y && pt.y < poly[j].y) || (poly[j].y <= pt.y && pt.y < poly[i].y))
&& (pt.x < (poly[j].x - poly[i].x) * (pt.y - poly[i].y) / (poly[j].y - poly[i].y) + poly[i].x)
&& (c = !c);
return c;
}
(either one will work if i could get them converted)
So, to try this out...I put the .h file and .c file into xcode with my iPhone project. The only question now is how to call this from Objective-C and get the result.. :)
BTW: I searched the Great God Google all last night to get the answer to this but just TRY to search for "including C in an Objective-C iPhone app", etc.. you get so many entries and none have to do with this! :) Just letting you know I tried google before posting here.
Okay, my issues:
How do I call the pnpoly from Objective-C?
What types do i call it using? (int is fine, but the float
*vertx is obviously an array of floats..which NSArray does not have
-- that I can find)
(EDIT: HERE IS MORE INFO. I AM ASKING FOR HELP CONTRUCTING THE ARRAYS THAT WOULD BE PASSED AS WELL)
The question was not asked fully.
The routine (in objective-c) would be like this: (assuming this is coded right)
NSMutableArray *latitudeArray = [[NSMutableArray alloc] init];
NSMutableArray *longitudeArray = [[NSMutableArray alloc] init];
// coordinates surrounding 1 inifite loop.
[latitudeArray addObject:#"37.32812557141369"];
[longitudeArray addObject:#"-122.0320253896318"];
[latitudeArray addObject:#"37.32821852349916"];
[longitudeArray addObject:#"-122.0289014325174"];
[latitudeArray addObject:#"37.33021046381746"];
[longitudeArray addObject:#"-122.0289300638158"];
[latitudeArray addObject:#"37.33042111092124"];
[longitudeArray addObject:#"-122.0279574092159"];
[latitudeArray addObject:#"37.33395972491337"];
[longitudeArray addObject:#"-122.0279263955651"];
[latitudeArray addObject:#"37.33363270879559"];
[longitudeArray addObject:#"-122.0320527775551"];
[latitudeArray addObject:#"37.32812557141369"];
[longitudeArray addObject:#"-122.0320253896318"];
int nvert = [[latitudeArray count] intvalue];
// 37.33189399206268 x -122.0296274412866 should return true
float testx =37.33189399206268;
float testy =-122.0296274412866;
int y_or_n = pnpoly(int nvert, float *vertx, float *verty, float testx, float testy);
I should've made it clear that I am learning Objective-c but FOUND that C routine--so was not sure how to construct either the C variables to call it with or the routine to call it with.
I know this is asking a lot...but it is really puzzling to me. Can anyone help me?
Thanks so much.
Jann
You can just call it. Objective-C is just a front-end to a C API and a way of re-writing methods as functions (to some approximation, anyway...) so you can call a C function just as you would in C code.
- (int)doWhatever {
// ...
int hitTest = pnPoly(/*blah*/);
return hitTest;
}
You can use C primitive types like int and float in Objective-C without issue, too. So call the function with floats :). If you need to store such values in Foundation collection classes like NSArray, then you can wrap them in a class called NSNumber.
NSNumber *someFloat = [NSNumber numberWithFloat: f];
float usefulValue = [someFloat floatValue];
Here's en example of how it would be used:
int nCoords = 4;
float vertexXCoords[n] = {0.0, 0.0, 20.0, 20.0};
float vertexYCoords[n] = {0.0, 20.0, 20.0, 0.0};
NSPoint testPoint = NSMakePoint(5, 10);
BOOL testPointIsInPoly = pnpoly(nCoords, xCoords, yCoords, testPoint.x, testPoint.y);
Note that there's nothing specific to Objective-C in here. This is C code (though it does use the Cocoa BOOL and NSPoint C types). Since Objective-C is a strict superset of C, any valid C code is also valid Objective-C. This is also a case in which Objective-C's unique features would not be particularly useful. (Numerical calculations in general are less complex and more readable in plain C.)
objective C is a superset of C, so you can call C routines. If you are calling that routine a lot, inline it or make it a macro.