Accessing methods from another class - iphone

I am new to the C objective and I'm having lots of difficulties. Hope you goys would be able to help me out.
Alright, I have a view controller class that displays the data from the external sensor plugged to an iphone. I have another database class that is supposed to grab that data and store it in an array which can be used to plot a graph.
I'm having difficulties in finding a way to capture the data captured by the view controller class method variables and using it to store in database class.
The code below is from View Controller class which captures analog signal and displays in UILabel.
(void) forceCalculationKg{
NSNumber *number = [controller. analogInValues objectAtIndex:0];
[controller enableDigitalInputs:YES];
double value = [number doubleValue];
double force;
force = 0.2908 *pow(2.718,(1.2089 * value));
double forcekg;
forcekg = force/2.2;
forceoutput.text = [NSString stringWithFormat:#" %0.1f", forcekg];
}

You didn't submit code for this question that actually compiles. But in any case, I assume your forceCalculationKg method is the function on your controller that you are calling to retrieve the sensor data? You are then applying a calculation to the data and displaying it, right?. To keep this data around, just add a NSMutableArray property to your controller and save each transformed data point to it.
-(void) forceCalculationKg {
NSNumber *number = [controller.analogInValues objectAtIndex:0];
[controller enableDigitalInputs:YES];
double value = [number doubleValue];
double force = 0.2908 *pow(2.718,(1.2089 * value));
double forcekg = force/2.2;
[self.datapoints addObject: [NSNumber numberWithDouble: forcekg]];
forceoutput.text = [NSString stringWithFormat:#" %0.1f", forcekg];
}
Where datapoints is a NSMutableArray property you add to your view controller via the #property and #synthesize keywords. You can then pass the datapoints array around your program to wherever you need it.

Related

objective c perform selector in background and autoreleasepool

I am developing an iphone application which has some data stored in a sqllite database. When my view loads i would like to load the data from the database on a background thread. The problem is the application keeps crashing and i dont know why.
The code:
-(id) init
{
if((self=[super init]))
{
[self performSelectorInBackground:#selector(loadList) withObject:nil];
}
}
-(void) loadList
{
#autoreleasepool
{
Loader * loader = [[Loader alloc] init];
NSMutableArray * array = [loader getItemList];
[array retain];
NSLog(#"Got %d items",[array count]);
[self performSelectorOnMainThread:#selector(createList:) withObject:array waitUntilDone:false];
[loader release];
}
}
-(void) createList: (NSMutableArray*) array
{
items = array;
int i;
Item * it;
for(i = 0; i < [items count]; i++)
{
it = [items objectAtIndex: i];
[it getName]; // crashes
// populate the list
}
}
Loader returns a NSMutableArray with Item objects. The application crashes when i call the item getName (which returns a NSString*). From what i understand it crashes because the item name properties is being released. What am i doing wrong?
Thanks!
It's likely to be a problem with whatever type of object you're using to populate array.
I'm unable to find finger-on-paper proof but I'm confident that performSelectorOnMainThread:withObject:waitUntilDone: retains its object. However if each of the items in array keeps a reference to loader then they need to take responsibility for retaining that object. It looks like you're attempting to keep it alive manually but — as Chuck alludes to — your call to performSelector... will return instantly and not wait for the call you've made to complete.
This particular bug appears to be that you're passing waitUntilDone:NO, so the array is being released immediately and consequently so are its items.
But in general, UIKit is not thread-safe, so this is just a touchy design. I would probably put the loading of this stuff in another class that handles the task for you instead of right in the view.
I'd put a breakpoint on the line:
it = [items objectAtIndex: i];
Then type
po it
in the debugger, and see what's in the name field. As a guess, I'd say one of two things: 1) the field that getName returns isn't initialized with an object (i.e. isn't a real NSString *) or that you're getting a C string from SQLite (which is what it usually returns) and you're trying to treat it as an NSString *. If it's the latter you can use [myCString stringWithUTF8String] to convert the C string into an NSString *

How to store NSTimeInterval values into a NSMutableArray?

I have a requirement where i have a Video that is played using MPMediaPlayerController. Along with the video i have two buttons where i need to capture the current playback time when the button are clicked and store all the relevant clicks individually. I am able to get the current playback time of the video using "currentPlaybackTime" property which returns NSTimeInterval. But can someone help me in how to store all the NSTimeInterval values into an NSMutableDictionary. I have tried the following ways:
-(void)onClickOfGood {
NSLog(#"The current playback time in good:%g",moviePlayerController.currentPlaybackTime);
currentPlaybackTime = moviePlayerController.currentPlaybackTime;
//NSArray *arrayContainsGoodClicks = [[NSArray alloc]initWithObjects:currentPlaybackTime, nil ];
NSNumber *goodTimeIntervals = [NSNumber numberWithDouble:currentPlaybackTime];
NSMutableArray *arrayContainsGoodClicks = [[NSMutableArray alloc]initWithObjects:goodTimeIntervals,nil ];
NSLog(#"The total count of Array is: %i",[arrayContainsGoodClicks count]);}
But everytime after the click of good button i am getting the Array count as only 1. Can someone please throw a light on where i am going wrong?
But everytime after the click of good button i am getting the Array count as only 1.
This is not surprising, considering that you are creating a brand-new NSMutableArray on the previous line.
To fix this, you need to make NSMutableArray *arrayContainsGoodClicks an instance variable (AKA ivar), initialize it to [NSMutableArray array] in your designated initializer, and then use
[arrayContainsGoodClicks addObject:goodTimeIntervals];
to add objects to the array.
If you are looking to use NSMutableDictionary instead, the strategy would be identical, except you would need to decide on an object that you would like to use as unique keys to your NSDictionary. Also remember that NSMutableDictionary is not ordered, so you might need to take care of sorting each time you display your dictionary items to users.
You need to create arrayContainsGoodClicks only once (in init method for example) and then add value to this array in your button handler:
//.h
NSMutableArray *arrayContainsGoodClicks;
//.m - init
arrayContainsGoodClicks = [NSMutableArray array];
//.m - button handler
[arrayContainsGoodClicks addObject:goodTimeIntervals];
You need to create your array and store it as a ivar.
#property (retain, nonatomic) NSMutableArray *clicksArray;
...
#synthesize clicksArray;
Now in your -init method create the array like..
self.clicksArray = [NSMutableArray array];
And add the object to the array each time so your -onClickOfGood would become something like...
...
[self.clicksArray addObject: goodTimeIntervals];
NSLog(#"The total count of Array is: %i",[self.clicksArray count]);

Filling an NSMutableArray with a Set of Classes and Then Getting them Back

Hopefully I can make this clear, but I am new to Objective-C and to be honest not great with Arrays in the first place.
So, I have a Singleton class (called SingletonState) that I am using to pass variables around my app (please can we leave the whether I should use Singleton classes out of this - I will fix that later). In this class, I have an NSMutableArray (called arrayMyEvents). I have also created a class that I am going to store a list of events (called EventClass). When the user logs in, I call a web service and get back 3 strings. The 3rd string is a comma separated list of value. I parse the data and populate the custom class EventClass. I then add this class to the SingletonState.arrayMyEvents.
I have all of this working. I can go to another ViewController and access the "count" of items in arrayMyEvents.
PROBLEM: I now want to edit one of the ScheduledEventsClass"es" in my array. How do I get access to it and edit some of the properties and update the one in my SingletonState class?
Here is some of the code, that I've tried:
NSString *sWebServiceEvents = [[NSString alloc] initWithFormat:#"%#", [result objectAtIndex:2]];
if ( [ sWebServiceEvents isEqualToString:#"NULL" ] != true ) {
NSArray *arrayEvents = [sWebServiceEvents componentsSeparatedByString:#","];
// If the array has not been initialized they initialize it.
if (sharedState.arrayMyEvents == nil) {
sharedState.arrayMyEvents = [[NSMutableArray alloc ] init ];
}
for (NSString * sEvent in arrayEvents) {
// Set equal to the value of the array (the Event Number) at the same
// position as the row that we are being asked to return a cell/row for.
EventClass *eventClass = [[EventClass alloc] retain];
eventClass.sEvent = sEvent;
[ sharedState.arrayEvents addObject:eventClass ];
}
NSLog(#"LoginView - sharedState.arrayMyEvents Count: %d", [sharedState.arrayMyEvents count]);
}
Here is me trying to access it in another ViewController:
EventClass *eventClass =
[sharedState.arrayMyEvents objectAtIndex:row ];
NSLog(#"eventClass.sEventNumber: ", eventClass.sEventNumber);
eventClass.sLocation = #"Jason's Big Location";
You're going to have some memory leaks from the sEvent loop. [[EventClass alloc]retain] leaves you an uninitialized EventClass object with a reference count of 2. You'll need to change that to [[[EventClass alloc] init] autorelease] to keep it from leaking. The arrayEvents NSMutableArray will retain it during the addObject: call. (Shouldn't that be [sharedState.arrayMyEvents addObject: eventClass] in the loop?)
After that, all you have to do to edit the EventClass object in the second block of code is edit it. The eventClass variable is a pointer to an object in the array. Anything done to that object doesn't affect the pointer referencing it, it affects data referenced by it. The code you have in the second block should change the sLocation of the selected object as you intend.
You have a few more memory leaks in there, too. Use Cmd-Shift-A to build with the static analyzer and it'll tell you where.
Maybe the problem is that you put them in sharedState.arrayEvents but try to take them out of sharedState.arrayMyEvents. Different variables.
Also, lots of memory leaks.
Thanks John and St3fan, your answers and time are appreciated!!!
I think that I figured out my issue:
Basically, the class that I created (EventClass) had the properties setup like this:
#property (nonatomic, assign) NSString *sStudyNumber;
#property (nonatomic, assign) NSString *sTheater;
but, they should be (or at least I got it to work like this):
#property (nonatomic, retain) NSString *sStudyNumber;
#property (nonatomic, retain) NSString *sTheater;
Then, in my second view I was able to do this:
EventClass *eventClass = [sharedState.arrayMyEvents objectAtIndex:row ];
NSLog(#"MyEvents: %#", eventClass.sEventNumber);
eventClass.sLocation = #"Jason's Big Location";
I then checked it in another method of the view using this and it was still there:
EventClass *eventClass = [sharedState.arrayMyEvents objectAtIndex:row ];
NSLog(#"MyEvents: %#", eventClass.sEventNumber);
NSLog(#"MyEvents: %#", eventClass.sLocation);
I also, checked it in yet another view and the value was maintained in the SharedState.arrayMyEvents without issue. :)
In the end, I believe that I boiled down to the difference between "assign" and "retain".
Now, on to the memory leaks :(
Please, let me know if you see any other issues with this.
Thanks,
Jason

replaceObjectAtIndex array problems

Been searching for the answer to this for a while now and I think due to the nature of my array set up, I may be searching for the wrong answer!
I have a class which handles adding items to my array:
// Item.h
#interface Item : NSObject {
NSString *name;
NSNumber *seconds;
}
#property(nonatomic,copy) NSString *name;
#property(nonatomic,copy) NSNumber *seconds;
- (id)initWithName:(NSString *)n seconds:(NSNumber *)sec;
#end
and...
//item.m
#implementation Item
#synthesize name, seconds;
- (id)initWithName:(NSString *)n seconds:(NSNumber *)sec {
self.name = n;
self.seconds = sec;
return self;
}
#end
So to add an item, I use
Item *item1 = [[Item alloc] initWithName:#"runnerA" seconds:[NSNumber numberWithInt:780]];
I have some code which allows a user to edit a textfield (runner name) and the time which is a UIdatepicker set to hours and minutes. In the save method, that's working fine. It's the UPDATE that I cannot get to work. I've tried alsorts! Here's the code at the moment...
mainAppDelegate *appDelegate = (mainAppDelegate *)[[UIApplication sharedApplication] delegate];
Item *item = [[Item alloc] initWithName:inputName.text seconds:[NSNumber numberWithInt:secs]];
[appDelegate.arrItems replaceObjectAtIndex:rowBeingEdited withObject:item];
The above is simply adding a new item to the array (which is what I don't want). I'm not sure how to replace values. At the function, I have the row I need to update (rowBeingEdited) and the fields inputName.text and secs are both OK. (NSLog out confirms this).
How do I use the replaceObjectAtIndex to actually replace it with the values?! It's driving me mad now!!
Since you are simply trying to edit a particular row, why not use those property accessors that you already have set up in Item? It would look something like this:
Item *item = (Item *)[appDelegate.arrItems objectAtIndex:rowBeingEdited];
[item setName:inputName.text];
[item setSeconds:[NSNumber numberWithInt:secs]];
An a side note, are you using garbage collection, or do you manually release the Item objects that you create when adding items to the array? If you are doing it manually, it should look like this:
Item *item1 = [[Item alloc] initWithName:#"runnerA"
seconds:[NSNumber numberWithInt:780]];
[appDelegate.arrItems addObject:item1];
[item1 release];
This follows the rule of thumb: if you alloc, copy or retain anything, you must also release it. Note that this works because the array will retain the item when it is added.
Are you using NSArray or NSMutableArray?
Assuming you are using NSMutableArray, how did you initialize and populate the array in the first place?
For example, it's not enough to use -initWithCapacity: or +arrayWithCapacity: which only sets aside space. You have to use -addObject: for the first round of population, before you can use -replaceObjectAtIndex:withObject::
Note that NSArray objects are not like C arrays. That is, even though you specify a size when you create an array, the specified size is regarded as a “hint”; the actual size of the array is still 0. This means that you cannot insert an object at an index greater than the current count of an array. For example, if an array contains two objects, its size is 2, so you can add objects at indices 0, 1, or 2. Index 3 is illegal and out of bounds; if you try to add an object at index 3 (when the size of the array is 2), NSMutableArray raises an exception.

Retrieve NSNumber From Array

I am relatively new to Objective C and need some array help.
I have a plist which contains a Dictionary and an NSNumber Array, with more arrays to
be added later on.
NSMutableDictionary *mainArray = [[NSMutableDictionary alloc]initWithContentsOfFile:filePath];
NSArray *scoresArray = [mainArray objectForKey:#"scores"];
I need to retrieve all the values from the array and connect them to 10 UILabels which
I've set up in interface builder. I've done the following to cast the NSNumber to a String.
NSNumber *numberOne = [scoresArray objectAtIndex:0];
NSUInteger intOne = [numberOne intValue];
NSString *stringOne = [NSString stringWithFormat:#"%d",intOne];
scoreLabel1.text = stringOne;
This seems a very long winded approach, I'd have to repeat the 4 lines above ten times to retrieve all the array values. Could I use a for loop to iterate through the array with all of the values converted to Strings at the output?
Any info would be greatly appreciated.
// create NSMutableArray* of score UILabel items, called "scoreLabels"
NSMutableArray *scoreLabels = [NSMutableArray arrayWithCapacity:10];
[scoreLabels addObject:scoreLabel1];
[scoreLabels addObject:scoreLabel2];
// ...
NSUInteger _index = 0;
for (NSNumber *_number in scoresArray) {
UILabel *_label = [scoreLabels objectAtIndex:_index];
_label.text = [NSString stringWithFormat:#"%d", [_number intValue]];
_index++;
}
EDIT
I'm not sure why you'd want to comment out _index++. I haven't tested this code, so maybe I'm missing something somewhere. But I don't see anything wrong with _index++ — that's a pretty standard way to increment a counter.
As an alternative to creating the scoreLabels array, you could indeed retrieve the tag property of the subviews of the view controller (in this case, UILabel instances that you add a tag value to in Interface Builder).
Assuming that the tag value is predictable — e.g., each UILabel from scoreLabel1 through scoreLabel10 is labeled with a tag equal to the values of _index that we use in the for loop (0 through 9) — then you could reference the UILabel directly:
// no need to create the NSMutableArray* scoreLabels here
NSUInteger _index = 0;
for (NSNumber *_number in scoresArray) {
UILabel *_label = (UILabel *)[self.view viewWithTag:_index];
_label.text = [NSString stringWithFormat:#"%d", [_number intValue]];
_index++;
}
The key to making that work is that the tag value has to be unique for the UILabel and must be something you can reference with -viewWithTag:.
The code above very simply assumes that the tag values are the same as the _index values, but that isn't required. (It also assumes the UILabel instances are subviews of the view controller's view property, which will depend on how you set up your interface in Interface Builder.)
Some people write functions that add 1000 or some other integer that allows you group types of subviews together — UILabel instances get 1000, 1001, and so on, and UIButton instances would get 2000, 2001, etc.
try using stringValue...
scoreLabel1.text = [(NSNumber *)[scoresArray objectAtIndex:0] stringValue];