Objective-C source code debug: Thread Error - objective-c

I cannot seem to solve this problem, im not sure what it is at this point but the tread error wont go away. I cant seem to find what im doing wrong.
This code may be a handful to read (sorry) but its very simple. I'am basically invoking a function from main and passing an array of function values, from there im passing two fractions at a time to a method so it find the LCM(least common multiple) using the denominators and return the value. But a thread error seems to be occurring at the call to the findLCM method from function at the point of where the method is declared.
#interface Fraction: NSObject
#property int numerator, denominator;
-(Fraction *)findLCM:(Fraction *)fraction withXFractions:(int)Xfraction;
#implementation Fraction
-(Fraction *)findLCM:(Fraction *)fraction withXFractions:(int)Xfraction{
int lcmOfFraction = 0;
int a, b;
a = fraction.denominator;
b = self.denominator;
int max =(a>b) ? a : b; // get max value out of the two denominators.
for (int i = 0; i < Xfraction; i++) {
while(1) /* Always true. */
{
if(max%a==0 && max%b==0)
{ lcmOfFraction = max;
break; /* while loop terminates. */
}
++max;
}
}
Fraction *lcmDenominator = [Fraction new];
[lcmDenominator setTo:0 over:max]; //passing just LCM (denominator of 2 fractions)
return lcmDenominator;
}
Fraction *addFraction(Fraction **arrayOfFractions, int arraySize) {
Fraction *LCM = [[Fraction alloc] init];
int lcmOfFractions = 0;
[LCM setTo:0 over:1];
for (int i = 0; i <= arraySize; i++) {
LCM = [LCM findLCM:arrayOfFractions[i] withXFractions:4];
//^gets the LCM (the common denominator)
}
return LCM;
}
int main () {
#autoreleasepool {
[frac1 setTo:2 over:12]; [frac2 setTo:2 over:4];
[frac3 setTo:6 over:8]; [frac4 setTo:8 over:3];
Fraction __autoreleasing *arrayOfFractions[4] = {frac1, frac2, frac3, frac4 };
Fraction *LCMFraction = addFraction(arrayOfFractions, 4);
//common LCM return
}
}

You create no threads in this code. When asking a question like this you should clearly explain what the error is, and what you have tried to find its source. People may then be able to help you.
Some hints/suggestions:
use breakpoints to stop your code during execution to allow you to examine the values of your variables
pay close attention to indexing operations, you are using a C array and those do not do bounds checking
ask whether using a C array here, rather than an NSArray is your best choice. Note there is nothing wrong with using C arrays when appropriate.
__autoreleasing probably doesn't mean what you think it does, it is rare to see this used explicitly in user code.
If you have a specific question when you've got further ask a new question on SO, somebody will probably be able to help you out.
HTH

Related

float array gives different datas at the end of it in objective c

I bumped to a strange error.(at least for me) I am trying to use float array in FFT and audio filters that I apply. but float array gives different datas at the end.
I define a global pointer. I point a float array to it. but when I try to use the pointer in somewhere out of the scope of a method, the last 100-150 datas of 441000 datas get mostly 0 or some other very big numbers. I dont understand how a data can change when I use somewhere in out of scope
in scope I loop in it and every data is correct but when I try to loop outside of the scope of the method I created the array, it gives different datas at the end.
#interface ViewController ()
{
float *filteredData;
int theFileLengthInFrames;
}
#end
#implementation ViewController
..
..
-(void)FilterData:(float * ) rawData
{
int count = theFileLengthInFrames;
float filteredRawData[count];
for (int i = 0; i<count; i++)
{
filteredRawData[i] = rawData[i];
printf("%d_%f ",i,filteredRawData[i]);
//I check here to see the data . In here it is normal
}
filteredData = filteredRawData;
}
-(void) CalculateFFT
{
int numSamples = theFileLengthInFrames;
for (int i = 0; i<numSamples; i++)
{
printf("%d_%f ",i,filteredData[i]);
//when I check here to see the data , the last around 100 data are 0.00000 or some big number such as 250399682724883753288597504.000000
}
}
need help thanks
Your FilterData: method points the instance variable filteredData to a local array filteredRawData. Since filteredRawData is allocated on the stack, it becomes invalid when FilterData: returns. Then filteredData is a dangling pointer, and using it results in undefined behavior.
Solution: allocate persistent storage for filteredData. I would do it like this:
#implementation ViewController {
NSMutableData *filteredDataStorage;
float *filteredData;
}
-(void)FilterData:(float * ) rawData {
int count = theFileLengthInFrames;
filteredDataStorage = [NSMutableData dataWithLength:count * sizeof *rawData];
filteredData = (float *)filteredDataStorage.mutableBytes;
for (int i = 0; i<count; i++) {
filteredRaw[i] = rawData[i];
printf("%d_%f ",i,filteredRawData[i]);
//I check here to see the data . In here it is normal
}
}
Using NSMutableData for the persistent storage lets ARC take care of deallocating it when you call FilterData: again, or when ViewController is deallocated.
filteredData - The float pointer is an ivar, it's scoped to your object instance.
filteredRawData is defined at method scope. It's an array located on the stack. When filteredRawData goes out of scope that memory is no longer valid. Reading from it is undefined at best and could result in an access violation. You probably want to use malloc to dynamically allocate memory for your data, or have a global buffer defined for you to play with.

Create an global array containing floating numbers

I wanted to create 2 global arrays which can be updated during the run of the programme.In each update i add one element to zeroth position and deleted the last number
I created the arrays as....
In the .h file..........
//////////////
#interface Shared : NSObject{
NSMutableArray *x;
NSMutableArray *y;
}
#property (nonatomic,retain) NSMutableArray *x;
#property (nonatomic,retain) NSMutableArray *y;
+(Shared*)sharedInstance;
#end
In .m file
staticShared* sharedInstance;
#implementation Shared
#synthesize x;
#synthesize y;
+(Shared*)sharedInstance
{
if (!sharedInstance) {
sharedInstance=[[Sharedalloc]init];
}
returnsharedInstance;
}
-(Shared*)init
{
self = [superinit];
if(self)
{
x=[[NSMutableArrayalloc] init];
x=[NSMutableArrayarrayWithObjects:#"0",#"0",#"0",#"0",#"0",#"0",#"0",nil];
y=[[NSMutableArrayalloc] init];
y=[NSMutableArrayarrayWithObjects:#"0",#"0",#"0",#"0",#"0",#"0",nil];
}
returnself;
}
#end
Then i used to call them and re,ove and added elements using the following code....
[[shared sharedInstance].y removeLastObject];
[[shared sharedInstance].y insertObject:new_element atIndex:0];
[[shared sharedInstance].x removeLastObject];
[[shared sharedInstance].x insertObject:new_element atIndex:0];
In the mean time i call these values and calculate an arithmetic value using an expression.
This seems to work well. But it seems to be an inefficient way to handle floating point numbers which i store in it. As these arrays creates objects. Is there any easy method that i can create a global array containing specified amount of floating point numbers and update it during the run of the programm(array size is fixed) by deleting the last object, and call them back to do calculation?
Please help me!
EDIT 1
To sir deanWombourne
.................................
I implement as you instructed! Can you please go through this and help me to correct 2 errors i get.
IN the .h file
#interface Shared : NSObject{
#private
float input[7];
float output[6];
}
+(Shared*)sharedInstance;
-(void)addNewInput:(float)input1;
-(float *)input;
-(void)addNewOutput:(float)output1;
-(float *)output;
#end
in .m file............
#implementation Shared
-(id)init{
if((self =[superinit])){
for(int n=0; n<7 ;++n)
input[n]=0.00f;
for(int n=0; n<6 ;++n)
output[n]=0.00f;
}
returnself;
}
-(void)addNewInput:(float)input1{
input[0]=input[1];
input[1]=input[2];
input[2]=input[3];
input[3]=input[4];
input[4]=input[5];
input[5]=input[6];
input[6]=input1;
}
-(float *)input {
returninput;
}
-(void)addNewOutput:(float)output1{
output[0]=output[1];
output[1]=output[2];
output[2]=output[3];
output[3]=output[4];
output[4]=output[5];
input[5]=output1;
}
-(float *)output {
returnoutput;
}
#end
When calling it
float reading= (accel_reading)/(1.165969038*1e5f);
[[SharedsharedInstance] addNewInput:reading];
Problems i get
1. In the implementation, it says incomplete implementation (it's a warning not an error)
2. How can i used a for loop to fill array values or is this way ok?
Major problem i get,
When i call it as shown above, program stops running telling
Terminating application due to uncaught exception 'NSInvalidArgumentException', reason '+[SharedsharedInstance]: unrecognized selector sent to class 0x5780'
Please help me through this...............
Your code Smells (and I mean that in the nicest possible way!)
Using two parallel arrays and keeping in sync is a bad design pattern (and a performance hit in quite a few ways!). Especially as there is already a struct that handles storing an x and y at the same time - CGPoint).
You're solving the 'only objects go in arrays' problem by converting your float' primitives toNSString` objects, which is horrendously inefficient - take a look instead at the NSValue class, it's designed to put native C primitives into an object without expensive parsing operations :)
You might also want to look into malloc (and free etc) and deal with the whole problem at the C level - this will mean no objects at all and would be blindingly fast (at the cost of more complicated code).
Hope this helps, if you have any questions just add a comment to this answer :)
EDIT
If all you want to do is store 4 x and y values, then this is probably the easiest way to do it :
#interface Shared : NSObject {
#private
CGPoint points[4];
}
+(Shared *)sharedInstance;
- (void)addNewPoint:(CGPoint)point;
- (CGPoint *)points;
#end
#implementation
- (id)init {
if ((self = [super init])) {
// Start with 0,0 for all your points
for (int n = 0; n < 4; ++n)
points[n] = CGPointZero;
}
return self;
}
- (void)addNewPoint:(CGPoint)point {
// Just move all the points along one and add the new one to the end
// (yes, this could be done in a loop but there's not that much point for 4 points!)
points[0] = points[1];
points[1] = points[2];
points[2] = points[3];
points[3] = point;
}
- (CGPoint *)points {
return points;
}
#end
This gives you a method addNewPoint that removes the first point and adds the new point to the end of your array.
You also get the method points that returns the 4 points. Use it something like :
// To add a point
CGPoint newPoint = CGPointMake(100, 100);
[[Shared sharedInstance] addNewPoint:newPoint];
// To do something with the points (in this case, NSLog them)
CGPoint *points = [[Shared sharedInstance] points];
for (int n = 0; n < 4; ++n)
NSLog(#" Point %i : %#", n, NSStringFromCGPoint(points[n]));
EDIT #2
From your comments, you need two arrays, one with input data and one with output data. Try something like this :
#interface Shared : NSObject {
float inputs[4];
float outputs[5];
}
...
This will give you two arrays to read/write to - one called inputs and the other called outputs. Access them in pretty much the same way you did the ones in my first edit :
float *inputs = [[Shared sharedInstance] inputs];
for (int n = 0; n < 4; ++n)
NSLog(#" Input %i : %f", n, inputs[n]);
float *outputs = [[Shared sharedInstance] outputs];
for (int n = 0; n < 5; ++n)
NSLog(#" Output %i : %f", n, output[n]);
Would a linked list be overkill for what you're trying to achieve? It's not quite as simple as a static array of floats, but makes the removal of the last object and insertion of the zeroth object reasonably simple and fast.
If you want an array containing a specific number of Objects, you can use NSArray, which is static, opposed to NSMutableArray.
As for the array being Global, just implement a singleton class that contains the 2 arrays and provides the associated methods.
in Globals.h:
#interface Globals : NSObject
+ (Globals *) sharedGlobals;
#end
in Globals.m:
#implementation Globals
static Globals *sharedGlobals = nil;
+ (Globals *) sharedGlobals{
#synchronized(self){
if (sharedGlobals == nil){
sharedGlobals = [[self alloc] init];
}
}
return sharedGlobals;
}
you then can access the arrays (after you implemented them) with the following line:
[[Globals sharedGlobals] getArrayX];
Here is a sketch to get you going.
Your array size is fixed and only contains floating point numbers, start with a C array:
double x[] = {0, 0, 0, 0, 0, 0, 0};
double y[] = {0, 0, 0, 0, 0, 0};
The number of elements in these arrays can be calculated rather than hard-coded:
int xCount = sizeof(x)/sizeof(double);
int yCount = sizeof(y)/sizeof(double);
Now use these arrays as a circular buffer, declare a cursor and initialise:
int xCursor = 0;
The item at the front of the queue is at the cursor:
valueAtFrontOfQueue = x[xCursor]; // get the current front item
To remove the value at front and add a new one to the rear replace the value at the cursor with the new value and increment the cursor:
x[xCursor] = newValueForBackOfQueue; // replace it with new item for back of queue
xCursor = (xCursor + 1) % xCount; // and advance cursor using mod arithmetic to it cycles around
No wrapping doubles as objects, no dynamic allocation at all.
Wrap the above up as you see fit, maybe as a class, and you're done.

Trying to make my objective-c program more efficient; Beginner

#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int number, right_digit;
NSLog(#"Enter your number.");
scanf("%i", &number);
while (number != 0) {
right_digit = number % 10;
if (right_digit <0 && number <10 && number>-10) {
right_digit = -right_digit;
NSLog(#"%i- ", right_digit);
}
else if (right_digit<0) {
right_digit = -right_digit;
NSLog(#"%i", right_digit);
}
else {
NSLog(#"%i", right_digit);
}
number /=10;
}
[pool drain];
return 0;
}
The aforementioned code works insofar as finding the reverse of a number, both negative and positive. If negative, say for example, -1234, the answer is supposed to read 4321-. I have no problems there. I am just learning Objective-C so I understand if this is a basic question and my code is very basic. The problem is I have some repeating code and I'm sure there is a better way to write this. I just wanted to know if someone could give me any insight.
I'd do it this way:
NSInteger number = -12;
NSUInteger inverse = 0;
NSInteger sign = (number >= 0) ? 1 : -1;
number = number * sign;
while (number > 0)
{
inverse = inverse * 10 + (number % 10);
number = number / 10;
}
NSLog(#"%i%#", inverse, (sign == -1) ? #"-" : #"");
Without critiquing the details of the algorithm (I might have done it differently, and I haven't evaluated it for correctness/robustness) I can't see anything that would be regarded as "inefficient".
Necessarily you're going to have to iterate through each digit, and you don't appear to iterate more than necessary. The logic is all (save for the actual output) "scalar" (not-object) integer values, so no unnecessary object creation. At most you might be able to eliminate one or two of the tests in your if statements, but there's little efficiency gain there. And I can't see how using any Cocoa classes might have made it simpler.

How to implement whileTrue control flow method with Obj-C Blocks?

Is it possible to implement something like a Smalltalk-style whileTrue: method in Objective-C using blocks? Specifically, instead of:
int count = 0;
while (count < 10)
{
NSLog(count);
count++;
}
I'd like to be able to do (via a wrapper on the bool primitive called OOBoolean) something like...
__block int count = 0;
[[OOBoolean booleanWithBool: count < 10] whileTrueDo: ^() {
NSLog(count);
count++;
}];
I'm having trouble understanding how this would be implemented though...
Here you have a couple of ideas,
Assuming your bool wrapper implements boolValue, a naive implementation could be:
-(void) whileTrueDo:(void (^)(void)) block{
while ([self boolValue]) {
block();
}
}
In order for the wrapper to change its bool value after each iteration, the block must be able to actually change the variable that is used to calculate the boolean condition. So, in your case, by setting the __block type modifier to count, and increasing count in each block execution, you should be able to make it work.
The problem is, if you create your wrapper by sending the evaluated condition, as you stated in your question, you wont be able to change its bool value in each iteration. So, I would change the way the wrapper is created and the whileTrueDo: naive implementation so the boolean wrapper uses an evaluation block.
__block int count = 0;
OOBooleanBlock evaluationBlock = ^BOOL{
return count < 10;
};
[[OOBoolean booleanWithBlock:evaluationBlock] whileTrueDo: ^() {
NSLog(count);
count++;
}];
//In OOBoolean
+(OOBoolean*) booleanWithBlock:(OOBooleanBlock) evaluationBlock{
//Instantiate, set the evaluationBlock ivar and return the ooboolean object.
}
-(void) whileTrueDo:(void (^)(void)) block{
while (self.evaluationBlock()) {
block();
}
}
Remember to use the __block type modifier, otherwise you will enter in an infinite loop.
I haven't tested this, I hope this helps you though.
Cheers

qsort on an array of pointers to Objective-C objects

I have an array of pointers to Objective-C objects. These objects have a sort key associated with them. I'm trying to use qsort to sort the array of pointers to these objects. However, the first time my comparator is called, the first argument points to the first element in my array, but the second argument points to garbage, giving me an EXC_BAD_ACCESS when I try to access its sort key.
Here is my code (paraphrased):
- (void)foo:(int)numThingies {
Thingie **array;
array = malloc(sizeof(deck[0])*numThingies);
for(int i = 0; i < numThingies; i++) {
array[i] = [[Thingie alloc] initWithSortKey:(float)random()/RAND_MAX];
}
qsort(array[0], numThingies, sizeof(array[0]), thingieCmp);
}
int thingieCmp(const void *a, const void *b) {
const Thingie *ia = (const Thingie *)a;
const Thingie *ib = (const Thingie *)b;
if (ia.sortKey > ib.sortKey) return 1; //ib point to garbage, so ib.sortKey produces the EXC_BAD_ACCESS
else return -1;
}
Any ideas why this is happening?
The problem is two fold:
the first argument to qsort needs to be a pointer to the beginning of the array
the arguments passed to your sort function are actually pointers to the pointers of your data
Consider this working code:
int thingieCmp(const void *a, const void *b) {
NSObject *aO = *(NSObject **)a;
NSObject *bO = *(NSObject **)b;
if (aO.hash > bO.hash) return 1;
else return -1;
}
int main (int argc, const char * argv[]) {
NSObject **array;
array = malloc(sizeof(NSObject*)*20);
for(int i = 0; i < 20; i++) {
array[i] = [NSObject new];
}
qsort(array, 20, sizeof(NSObject*), thingieCmp);
return 0;
}
Note that the comparison function resolves the data pointers by NSObject *aO = *(NSObject **)a and the qsort function takes array as an argument directly.
All of this, though, begs the question of Why bother?
NSArray is very good at holding arrays of objects and is quite conveniently sortable. Performance is excellent in the general case. If performance analysis indicates that it isn't, you can optimize it away relatively easily.
Note, also, that I have been consistent in use of sizeof() -- same type in both places. Also, the const in your original code is not necessary.
I think, one mistake lies right in the line
qsort(array[0], numThingies, sizeof(array[0]), thingieCmp);
Try
qsort(&array[0], numThingies, sizeof(array[0]), thingieCmp);
or even
qsort(array, numThingies, sizeof(array[0]), thingieCmp);
instead. The compiler won't complain here, as qsort is supposed to take a void* and you pass it a Thingy* which can legally be cast to void* without warning, but you really want qsort to operate on the entire array, which has type Thingy**.
Another thing is: the comparator will be called with pointers to the array slots as arguments, so what you get is actually a Thingy**:
int
thingieCmp(void* a, void* b)
{
Thingie *ia = *((Thingie**)a);
Thingie *ib = *((Thingie**)b);
...
}