UISlider how to set the initial value - iphone

I'm pretty new at this iphone dev stuff and i'm working on some existing code at a company. The uislider i'm trying to set the initial value on is actually in a UITableViewCell and is a custom control. I was thinking in the cell init
cell = (QuantitiesCell *)[self loadCellWithNibName:#"QuantitiesCell" forTableView:ltableView withStyle:UITableViewCellStyleDefault];
i could just call something like
((QuantitiesCell *)cell).value = 5;
The actual QuantitiesCell class has the member value and the following functions
-(void)initCell;{
if (listOfValues == nil) {
[self initListOfValues];
}
quantitiesSLider.maximumValue = [listOfValues count]-1;
quantitiesSLider.minimumValue = 0;
quantitiesSLider.value = self.value;
}
-(void)initListOfValues;{
listOfValues = [[NSMutableArray alloc] initWithCapacity:10];
int j =0;
for (float i = minValue; i <= maxValue+increment; i=i+increment) {
[listOfValues addObject:[NSNumber numberWithFloat: i]];
if (i == value) {
quantitiesSLider.value = j;
}
j++;
}
}
like i said, i'm pretty new at this so if i need to post more of the code to show whats going to get help, let me know,
This slider always is defaulting to 1, the slider ranges usually from 1-10, and i want to set it to a specific value of the item i'm trying to edit.

Setting slider.value is the correct way if your linkage is correct (you have made the connections in Interface Builder). If you have created a UISlider in code, all you have to do is set the value property. If that is not working then be sure firstly that the object is "live" (correctly allocated, not released, not out of scope etc.) and secondly that the functions in which you set slider.value are actually being called.
If you are using Interface Builder and are not sure of how to connect your slider as an IBOutlet, you should check out iTunes University - search for "CS193P" to find some excellent videos from Stanford University. The first couple will take you through making those connections. If using IB and you have not made the connection - nothing will happen.

PS I had the same issuer - you need to add the UISlide view first then you can change the value.

Related

EXC_BAD_ACCESS when setting Integer to anything else than zero

I have this object:
#interface Song : NSManagedObject
#property (nonatomic, strong) NSString *songName;
#property (nonatomic) int32_t achievedPoints;
When I set the properties like this
Song *song1 = [[SongStore sharedStore] createSong];
song1.songName = #"Song 1";
song1.achievedPoints = 0;
everything works, however once I try to set the achievedPoints variable to something else than 0 I get an EXC_BAD_ACCESS.
This is what the createSong method does:
- (Song *)createSong {
double order;
if ([allSongs count] == 0) {
order = 1.0;
} else {
order = [[allSongs lastObject] orderingValue] + 1.0;
}
Song *p = [NSEntityDescription insertNewObjectForEntityForName:#"Song" inManagedObjectContext:context];
[p setOrderingValue:order];
[allSongs addObject:p];
return p;
}
I have no idea why getting the value and setting it to 0 works but anything else than zero crashes the program. Any help is highly appreciated.
This has happened to me once before. I don't know exactly which settings gets messed up, but there is a setting in your managed object model, I think, that controls whether or not the class should use primitive values (int, float, etc) or object values (NSNumber *, etc) to set its values. If this gets messed up, and you think you are setting a primitive when you are actually setting an object the following will happen:
//song1.achievedPoints = 0;
song1.achievedPoints = (NSNumber *)0x00000000;
//This is OK because it is the same as nil
//song1.achievedPoints = 1;
song1.achievedPoints = (NSNumber *)0x00000001; //You can see why this is bad!
My solution was to regenerate the class via the Create NSManagedObject Subclass template, making sure that Use Scalar Values for Primitives was checked.
This issue happened to me because the entity wasn't correctly linked to my class files. When this happened, Core Data creates its own subclass dynamically, rather than using my own, and that subclass's setters expect boxed primitives.
You can fix this by ensuring the "Class" property of your entity in the model file is set to the correct class, and not the default NSManagedObject.
When you use XCode's Create NSManagedObject Subclass template, XCode will automatically set this value for the corresponding entity in the model file. This is probably what fixed borrrden's problem. However, you should be able to achieve the same result without creating new files by ensuring this value is set correctly.

How do I save values from a UITextField in the FlipsideViewController and use them in the MainViewController?

SEE EDIT AT BOTTOM
I am making a UtilityView application for the iPhone and I want to be able to change values from the FlipsideViewController. I have a problem that whenever I switch back to the MainView from the FlipsideView, the values of the text fields that I had changed in the FlipsideView are seemingly reset to 0. In the MainViewController.m, under the flipsideViewControllerDidFinish:
playToInt = [controller.playTo.text intValue];
computerMoveSpeed = [controller.aiSpeed.text intValue];
The text field 'playTo' coordinates with the integer 'playToInt' and the text field 'aiSpeed' coordinates with the integer 'computerMoveSpeed'. I think this should save the values, even when the ViewDidLoad runs again, but they both seem to be reset to 0.
if (playToInt != 10 || computerMoveSpeed != 3)
{
playBool = true;
}
else
{
playBool = false;
}
I know that the boolean is working because I can change the integers' values with it, but they always default back to 0. Any help is appreciated. Thanks in advance.
NOTE: I have consulted the previous question 'Passing UISegmentedControl values from FlipSideViewController in an Utility application to the mainviewcontroller…' and that does not work for me... I am have too many possible values to use an index or a switch.
EDIT: I am trying something that I think is really close to working... I feel like it just has bad syntax or something... I have in the MainViewController.m:
computerMoveSpeed = [FlipsideViewController.aiSpeed.text intValue];
playToInt = [FlipsideViewController.playTo.text];
EDIT: I have something that is similar to the last one but I think it will have a better chance of working with some help...
in the FlipsideViewController.m I have
_playToNumber = [_playTo.text intValue];
and in the MainViewController.m
playToInt = [controller.playToNumber];
Any help is greatly appreciated, but as some additional info, on the string in the MainViewController it says it needs an identifier on the playToNumber variable, but it is declared as int... I don't know if there is an identifier for ints but if there is, please let me know!
EDIT: Is there any way to save the values in a usable format for the MainViewController using the prepareForSegue function in the FlipsideViewController?
EDIT: I figured out that it was just getting the initial values when it loaded the ViewDidLoad, so I started using a timer to retrieve the values. This seems to be working, I just need to know how to access these values from the MainViewController?
Use delegate to send values back to MainViewController. See this tutorial to learn how to use delegates.
You have many way to do this task,
1. NSUserDefault
Follow ma answer Link
2. Using Getters, setters, property
Follow ma answer Link
EDIT
If you want int or NSInteger then no need for retain
just do
#property(nonatomic) NSInteger YourIntValue;
and
_playToNumber = [_playTo.text intValue];
MainViewController *MVC = [[MainViewController alloc] init];
MVC.playToInt=_playToNumber;
[self.navigationController pushViewController:MVC animated:YES];

Recycling labels in for loop and releasing them

What's the correct way of creating an UILabel and releasing it again when I want to re-use this until i'm out of records in my array?
I wanted to this this:
// create label
UILabel *labelIWishToRecycle;
for (int i = 0; i < [myArrayFullOfItems count]; i++) {
// Edit the label
labelIWishToRecycle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 640)];
}
// Release label
[labelIWishToRecycle release];
When I do it this way I get a crash for releasing it. So I just don't release it. Works like a charm now. Of course, this is not the way, so I was wondering what IS.
Should I create and release the label for every item in the array? Or should I create it outside the for-loop but release it within? Or ...?
Thanks in advance.
For what are you using the label!? If you are adding it to a view, than you have to use a new instance everytime.. if you only do size calculations or stuff like that, than you could use the same label over and over again.
But the trick is to initialize your local variable:
UILabel *labelIWishToRecycle = nil;
If you have done this, it is save to send release on it (also if no real label has been assigned yet). Before, your pointer is pointing on a random address and you are trying to release the object at that address. That will be a crash in the most cases.
(Guessing the problem case is the one, when your array count is zero.)

Cast NSString to UIButton type

Im trying to cast a string to a button type. Basically, Im looping through, say 5 buttons, named btn1,btn2..btn5. Here's the snippet:
- (IBAction)replaceImg
{
UIButton* b;
for(int i=0; i<5; i++)
{
b = (UIButton*)[NSString stringWithFormat:#"btn%d",i]; //1!
if([b isHighlighted])
{
int imgNo = (arc4random() % 6) + 1;
UIImage *img = [UIImage imageNamed:[NSStringstringWithFormat:#"%d.png", imgNo]];
[b setImage:img forState:(UIControlState)UIControlStateNormal];
}
}
}
The line marked 1 is giving a problem, if I swap it with b = btn1, it works perfectly. Please help!
I couldnt find a way to access a button by its name either. Like UIImage has something like imageNamed.
you can't cast NSString to UIButton because both are completely different type.
Use tag property of UIView to assign and unique number to each UIButton and at any point of time you could access them by using viewWithTag .
You can't 'cast' an NSString to a button. To get specific buttons, or buttons by name, depends on how you created them. Store your created buttons into an array, or if they come from a NIB then gather their pointers into an array, then loop through the array of button pointers. Controls are also UIViews, so you can assign a numeric 'tag' to each button in Interface Builder then use UIView's viewWithTag: method to search for a specific view with a specific tag.
An NSString isn't a UIButton, so casting it to one isn't going to work. Well, it might work as far as syntax goes, but logic-wise, it will fail. You simply cannot interact with an NSString the same way you can a UIButton. If you need to find your button by name, then you can either retain pointers to those buttons (either in an array, a map, or just as plain instance variables, to name a few ways), or you could alternatively use something like viewWithTag:.

Simple iPhone tally method question

Just trying to create a simple method that counts up 1 on the tally when the button is pressed. My knowledge is extremely limited and I am pretty sure that my problem is somewhere in the method implementation:
-(IBAction) updateTally:(id) sender {
NSString *text;
int total = 0;
total = total + 1;
text=[[NSString alloc] initWithFormat: #"%i", total];
lblTally.text = text;
}
I have done the necessary interface declarations for the lblTally UILabel and the updateTally method. I suspect that there is some sort of an NSString/int/%i/%# mixup that I am making but I'm not sure how to fix it. When I run the program as it currently is it displays a 0 in the lblTally label field on the iphone. When I press the button it then displays a 1 in that field. However, if I continue to press the button - nothing happens, it just remains a 1. How do I make it count up as I continually press the button over and over?
The problem is that you are reinitializing the total in each updateTally. You need to either store the tally in a member variable or extract the existing tally from the string, update it, then write it back to the string.
- (IBAction) updateTally:(id) sender
{
int oldtally = [lblTally.text integerValue];
int newtally = oldtally + 1;
lblTally.text = [NSString stringWithFormat:"%d",newtally];
}
I should also point out that your current code has a memory leak (you invoke alloc/init, but then you don't invoke release after you have assigned the result to the lblTally.text variable). You should either invoke [text release] after lblTally.text = text, or you should use stringWithFormat like I have used above, which uses autorelease so that the string does not need to be explicitly released (since it will be automatically released).
You are re-initialising the total variable each time the method runs.
int total = 0;
Move than line of code outside of the method. I dont do apple development but it'll be something like:
int total = 0;
-(IBAction) updateTally:(id) sender {
NSString *text;
total = total + 1;
text=[[NSString alloc] initWithFormat: #"%i", total];
lblTally.text = text;
}