How do I convert this to Objective-C?? Mainly this: float *newH= new float[newD];
What do I substitute new for in obj-c??
int newD = 100;
float *newH = new float[newD];
for(int i=0; i<newD; i++){
newH[i] = 0.0f;
}
Objective-C is a true superset of C. In C, one uses malloc to allocate memory.
So,
float *newH = malloc( newD * sizeof( float) );
Of course, depending on what you are really doing, you may also want to investigate NSArray and NSNumber.
Note, that Objective-C++ is available as well and you can continue to use 'new' to allocate your memory.
If you have a lot of C++ code to port, you might be better off writing your app in Objective-C++. Then you can use your C++ code as is.
I agree that Objective C++ is the way to go. However, if you absolutely want to stay within the spirit of Objective C (not straight C), here are the options:
use an NSArray of NSNumber objects. This is slow - float boxing penalty applies.
use a NSData as a allocation mechanism, cast [bytes] to float *. This is ugly, the way pointer typecasts are.
Related
I am having some problems dynamically declaring a GLfloat array in Objective-C. Here is the c
ode i'm using:
GLfloat *m_bindPositions;
#implementation
int nVerts = [self m_countVertices];
m_bindPositions = (GLfloat*)malloc((nVerts * 3) * sizeof(GLfloat));
nVerts in this example equals 6704.
if I was to run sizeof(m_bindPositions) it should return 80448.
It currently returns 4.This makes me believe there is an error with the allocation of the
memory and I am not entirely sure why. Any help would be much appreciated.
Thanks
sizeof in this case is returning the size of the pointer, not the data pointed at by it.
However, the compiler is what handles sizeof, and it will not dynamically return values based on malloc, so you cannot double-check an allocation like that using sizeof (or anything else, other than malloc_size(), which will return a number equal to or greater than the allocation, representing the allocation block size.
I'm a beginner with iPhone dev in Objective C and one thing I find I'm doing quite a lot is getting floats (and ints) in and out of various NSArrays
float myFloatValue = [(NSNumber *)[myArray objectAtIndex:integerSelector] floatValue];
I understand that I need to do this boxing because a float (or int) isn't a pointer and the NSArray accepts only pointers.
I'm just wondering if there a little bit of syntactic sugar to shorten this line of code - mostly because when I have a couple of arrays and I'm looping over them to do some processing I find that the lines start getting massive and I have to break out the lines that extract the number form the array just to make the code readable - then I have a lot of gumph lines that tend to make the logic harder to follow.
In a language like C# I would write something like
float myResult = myArray[i] + someOtherArray[i+1];
(ok - that's probably a pretty dumb line of code - but syntactically it's quite clean, I guess because .net is doing the boxing implicitly where I can't see it)
in objective C I find myself writing:
float myFloatValue = [(NSNumber *)[myArray objectAtIndex:i] floatValue];
float myOtherFloatValue = [(NSNumber *)[someOtherArray objectAtIndex:i+1] floatValue];
float myResult = myFloatValue + myOtherFloatValue;
I'm just wondering if I'm missing a trick here by typing it all out longhand. Should I be using an alternative to NSArray? Is there a shortcut for the boxing/unboxing?
Or I guess, should I just get used to it and stop whinging ;)
You can create a category:
#class NSArray (FloatHelper)
- (float) floatAtIndex:(NSUInteger)i;
#end
#implementation NSArray (FloatHelper)
- (float) floatAtIndex:(NSUInteger)i {
return [[self objectAtIndex:i] floatValue];
}
#end
(Untested and has no error handling, which, obviously, is not a good idea.)
Then it could be used as follows:
float a = [array floatAtIndex:1];
I don't think there is any shorthand for that, by the way
float myFloatValue = [[myArray objectAtIndex:i] floatValue];
is legal.
Unfortunately Objective-C doesn't support Auto-Boxing.
For more info please visit to link -Aotoboxing in objective c?
You can create a category, a function or a macro to do this with less verbose code.
But if you are doing this in a loop that consumes significant CPU time (as determined by profiling with Instruments), you should consider using a C array instead, which can be accessed using far less CPU cycles, thus conserving the users battery life. If you are touching the same elements multiple times, it might even be an optimization to copy all these floats from an NSArray to a plain C array of floats before doing your computation loop.
Why don't you create a macro,
#define _floatValue(array, index) [(NSNumber *)[array objectAtIndex:index] floatValue]
use it,
float myFloatValue = _floatValue(myArray, i);
float myOtherFloatValue = _floatValue(someOtherArray, i+1);
float myResult = myFloatValue + myOtherFloatValue;
and just stop bothering yourself?
I've searched the forum and seen some possible partial solutions to this question, but I'd like help putting it all together.
I'm getting the frames from the camera and doing image processing on the difference between the current frame and previous frame. In addition to the RGB values from the camera, I'm also calculating Hue and Saturation for each pixel, each of which is also an int. So my 2 questions are:
What is the best way to store all of these values from each call to didOutputSampleBuffer? From what I've been reading, it seems like with this many values, the overhead from NSNumber will be noticable so least memory would be spent using a classic c-style array of ints w/ length 144 x 192 x 5(R,G,B,H,S) = 138,240. Does that make sense?
How do I put this array in the scope of my didOutputSampleBuffer method, because I'm initializing the array upon app launch, not in the didOutputSampleBuffer method. Someone on the forum mentioned perhaps I could wrap the array in NSMutableData and then i could just store it as a property?
Thank you for your advice,
Don
Given that the size of an image won't change, you should be able to create a buffer to store these components as interleaved bytes or a few buffers for each color component plane. You could do this by manually using malloc() and free() to create this buffer and destroy it when done.
If you'd prefer to use reference counting, you could wrap these bytes in an NSData instance, which won't add much overhead to your processing. Either a pointer to your processed buffer bytes or an NSData instance could be used as properties.
Note that you'll probably want to use unsigned char types for each component, because you're only getting back individual bytes for each of the color components. Why waste memory with unnecessary precision?
Yes, that is a good way to store the data. Alternatively, you could use a c array of structures (see my example).
You could use a global variable or a property, containing either a NSMutableData object or the pointer to the array. Since you want access to the data as integers and not raw data, storing the pointer to the data would probably be easier than a NSData object.
Example:
// header file
struct PixelData {
int r, g, b, h, s;
};
#interface TheClass : TheSuperclass {
struct PixelData *dataPointer;
}
#property struct PixelData *dataPointer;
#end
// implementation file
#implementation TheClass
#synthesize dataPointer;
- (void)didOutputSampleBuffer { // Yes, I know this isn't the full name.
// parse data
// store data for pixel at index i:
struct PixelData *dp = self.dataPointer;
dp[i].r = r;
dp[i].g = g;
dp[i].b = b;
dp[i].h = h;
dp[i].s = s;
}
#end
When I was dealing with a similar problem I simply made the c style array an ivar on an object.
This way I could attach additional properties to it like metadata, etc.
#interface MyObject : NSObject {
int *arrayOfInts;
}
#property (readwrite) int *arrayOfInts;
#end
You still have to explicitly manage the memory in this case.
I have 2 NSArray (Mutable, actually) that I am trying to convert to a C-style double array for a c routine i am passing them to.
Here is my Objective-C routine:
NSMutableDictionary *childDictionary = [myParentDictionary objectForKey:resort_code];
latitudeArray = [childDictionary objectForKey:#"lat"];
longitudeArray = [childDictionary objectForKey:#"lon"];
int nvert = [latitudeArray count];
double laArray[nvert];
double loArray[nvert];
for(int i=0; i<nvert; i++) {
double dLat = [[latitudeArray objectAtIndex:i]doubleValue];
double dLon = [[longitudeArray objectAtIndex:i]doubleValue];
laArray[i] = dLat;
loArray[i] = dLon;
}
This takes upwards of 3-8 seconds on the 3G iPhone (instantaneous on the simulator -- yet another reason to test on the device )
is there faster way? I have to end up with laArray[i] and loArray[i] as c-style arrays of doubles.
(to expand on the question for the benefit of a commenter):
Each array consists of #"38.448745" (lat) and #"-122.9847684" (lon) style content. I do this cos to be pushed onto an NSArray, the lat and lon need to be objects. I simply used:
[latitudeArray addObject:[NSString stringWithFormat: #"%.10f",dlat]];
[longitudeArray addObject:[NSString stringWithFormat: #"%.10f",dlon]];
I suppose I could change that to:
[latitudeArray addObject:[NSNumber numberWithDouble: #"%.10f",dlat]];
[longitudeArray addObject:[NSNumber numberWithDouble: #"%.10f",dlon]];
...which may reduce the conversion time of
double dLat = [[latitudeArray objectAtIndex:i]doubleValue];
but wouldn't I still need that exact line to convert from NSString to double? It just may work faster?
thx
dlat is a double, right?
So instead of:
[latitudeArray addObject:[NSString stringWithFormat: #"%.10f",dlat]];
Do:
[latitudeArray addObject:[NSNumber numberWithDouble:dlat]];
They both respond to doubleValue but the NSNumber should not have to do any string parsing since it's stored as a numeric value already. And you never have to go to a string at all.
I suspect you have an array of strings like #"213.12385" that need to be parsed and converted when you call doubleValue on them. If that is where the issue is, the C arrays have nothing to with this.
Only thing I would add here is to throw Shark on this and see where it's spending it's time. If it's spending time in doubleValue find a different way to parse the strings with preprocessing in background or something. If it's in objectAtIndex: perhaps fast enumeration would help. If it's somewhere else entirely then you know it's not this snippet that's slow.
For the general case of converting an NSArray to a C array, you can use getObjects:. In this case, though, want you actually want is not to convert the NSArray, but to derive an array of doubles from an NSArray of some unspecified object type.
One obvious way to speed things up would be fast enumeration rather than sending a message to get the object for each iteration of the loop. I suspect the real solution, though, is outside your algorithm. The slowness probably comes from transforming whatever objects the array contains into doubles, in which case you'll need to find a way around that — maybe store doubles all along, maybe do the conversion in the background, etc. If you're creating the arrays yourself and there isn't some compelling reason for the objects to be strings, you should use NSNumbers instead. Those should be quite a bit faster.
The best solution is probably to make sure those values never end up in an NSArray as NSString values. I would attack this at the source.
So you edited your question and added that you are actually building those arrays. So why not use native arrays of doubles or floats from the start? I usually recommend against this but in your case it sounds like there is a huge performance gain.
Possibly using fast iteration, but I doubt that will really speed up your loop.
I have a CGFloat that contains only "integers", in the meaning that it actually wants to represent integers only but due to float inprecision it may happen that it internally has a 23.00000000000000000000000142 or something like that. I try to feed an NSDecimalNumber with clean input, so I need to make sure this is truly a naked integer with no dirt. Well, I think this is a good way, but maybe I am wrong:
NSInteger *intVal = floatVal;
That would just get rid of those fragmental parts at the end of the tale, right? Or is there a more secure way to convert it into a true integer?
If you just want to take the integer part of a float then I believe you can just do the following:
CGFloat myfloat = 23.0000000000142f;
int myInt = (int) myfloat;