How do I receive the current value of a slider in code? - objective-c

I am (attempting) developing my first application in Xcode using cocoa framework.
I have a slider which min value is 10 and max is 50. This is to select max search results.
I have linked a label on my user interface to display the value of the slider and when it is moved, it updates the label on the user interface.
However, I am trying to join around 4 strings to create my final URL one of them is the value of said label.
I am trying to read the value of the label on the interface for use in creating the finished URL
NSString *startofURL = #"http://starturl.com/?q=";
NSString *searchTerm = whatToSearch;
NSString *middleofURL = "&max-results=";
NSString *resultsStr = labelMaxResults.stringValue; //Problem here ??
I have 2 questions; firstly, How do I go about retrieving the value of my slider via code instead of trying to get it from the linked label, as I think this is my problem.
secondly, I have read up on joining and appending strings, however I am a little confused on which is the best method to use in order to join up the 4 strings into one long URL.

NSSlider * slider = [[NSSlider alloc] init];
[slider setMinValue:50];
[slider setMaxValue:150];
int sliderValue = [slider intValue];
this doesn't put your slider on screen, but assume you made it in IB, ignore the first line, you can set your min max and get the value.
you can make an action like
-(IBAction)sliderMoved:(id)sender
then bind that to the slider, if you set the slider to continuous you will get updates every time that it moves other wise just when you let go of the slider
-(IBAction)sliderMoved:(id)sender
{
sliderValue = [slider intValue];
[self doSomethingElseNow];
}

For the first part of your question, it depends which OS you are using as to which process to use.
If you are using OS X, the best way to get a value for your slider is to create a binding in IB for your slider. To do this, click on the slider in IB and go to the bindings section. In the Value section, click on Value and select the class you wish to use the value in as your Bind To class (I'm going to use MyClass for this example). Then for the model key path, assign it to some value of your choice. For the purpose of this, I'll just call it sliderValue.
Then in MyClass.h, you must set up the following:
#interface MyClass : <your class type> {
int sliderValue;
}
#property (readwrite, assign) int sliderValue;
In MyClass.m, you'll need to synthesize the value.
#synthesize sliderValue;
At this point, you should be able to get the value of your slider at any point in your code by calling [self sliderValue].
If you are, however, using iOS, then all you have to do is call the value property from your slider. So if you have the a UISlider *mySlider, all you have to do is call mySlider.value to get the current value of your slider.
For your second question, you can go about this two ways. If you want to append the strings, simply follow the format:
NSString *appendedString = #"";
appendedString = [appendedString stringByAppendingString:string1];
and so on until you have all your strings into your URL.
In your case, I would personally set up the entire URL string as a stringWithFormat:
NSString *urlString = [NSString stringWithFormat:#"http://www.starturl.com/%#%#%#", whatToSearch, middleOfURL, resultsStr];
Insert the values you want into the URL that way by setting up whatToSearch, etc., to the values you want. This way, you don't have to worry about appending everything together

Your code should look like this:
NSString *urlString = [NSString stringWithFormat:#"http://starturl.com/?q=%#&max-results=%f", whatToSearch, [slider floatValue]];
EDIT: Corrected my answer. For UISlider it should be value property. For NSSlider you should use - floatValue method

Related

Compare WKInterfaceLabel Text to Another NSString

I know there is no getter method for WKInterfaceLabel, but is there another way for me to compare the label text to another string? If this wasn't a watch app and I was using UILabel I could just do this:
if ([self.label.text isEqualToString:someString]) {
}
There's no supported way to get the text, just as you said, however you may want to use the accessibility elements as "option".
Here's the idea:
When self.label text is set (either in code or storyboard) also set the corresponding accessibility label/value. When you need to read/update the label text, just make sure you use the accessibility values instead.
self.label.text = #"foo";
self.label.accessibilityValue = #"foo";
if ([self.label.accessibilityValue isEqualToString:someString]) {
self.label.text = #"bar";
self.label.accessibilityValue = #"bar";
...
}
Plus it's how you would use accessibility anyway so it's legal. There may be other ways to accomplish, but this seems to be the quickest and safest way to do what you want.

Execute selector to find UIImageView using concatenated NSString

I'm new to Objective-C so sorry if this is a newbie question.
I've searched for a couple of hours and can't seem to find an answer to my question.
So I'm trying to access a UIImageView so I can hide/unhide it by concatenating strings together to get the name of the UIImageView which should hide/unhide.
I have it working by doing:
self.faceItemEyesFrightened.hidden = false;
However the Frightened part of the name could be different each time a button is clicked so, trying to refactor my code I run a function which returns the type of UIImageView should be affected.
So I have the following:
NSString *fullEmotionString = [#"faceItemEyes" stringByAppendingString:emotionIs];
where emotionIs would be Frightened, therefore forming
faceItemEyesFrightened
So my problem comes when I wish to do something like this:
self.fullEmotionString.hidden = false;
Obviously that's not the right way of doing it but I'm not sure how it should be done, any advice greatly appreciated.
Cheers!
You could use NSSelectorFromString like this:
SEL selector = NSSelectorFromString(fullEmotionString);
UIImageView *imageView = [self performSelector:selector];
imageView.hidden = NO;
Note, that this requires a getter called faceItemEyesFrightened to be defined, which is usually this case if you're using properties and didn't change the name of the accessors.
That being said, I think this is not an optimal solution to your problem.
You could for instance subclass UIImageView and add an enum MyImageViewEmotion that describes the emotion in the image. Then, instead of using lots of variables, like faceItemEyesFrightened or faceItemEyesHappy, you could put all of them in a simple array and then get one of them like this:
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self.emotion == %ld",
MyImageViewEmotionFrightened];
MyImageView *imageView = [eyeImageViews filteredArrayUsingPredicate:predicate][0]
Of use an NSDictionary, where you put the emotion string as the key and the image views as the value. Then you could access them very easily:
UIImageView *imageView = emotionViewDictionary[#"Frightened"];
By the way, boolean values in Objective-C are called YES and NO and not true and false.

How to choose a method based on an element of an NSArray (Objective-C)

I'm writing a sort of calculator app. I have a UIPickerView (1 column) loading data from an NSArray of strings. The user will select one of these (it's selecting which type of calculator to use -- each uses a different method to calculate). The user inputs some things into some UITextFields and then presses a UIButton to do the calculations.
My NSArray is this:
calcNames = [NSArray alloc] initWithObjects:#"first", #"second", #"third", nil];
And my methods are called firstCalc(input1, input2, input3), secondCalc(input1, input2, input3), and so on. (The inputs are coming from the UITextFields.)
When I press the button, I would like to tell it to look at what the selection in the UIPickerView is and run the corresponding method without just typing an if-then statement for each one (it's very inconvenient to do this for reasons specific to my app, which are beyond the scope of this discussion).
So I have already defined a way to determine what the selected calc is:
selectedCalc = [[NSString alloc] initWithString:[calcNames objectAtIndex:row]]
where 'row' is the current selection in the UIPickerView.
Now I have a doCalculations method for when someone presses the UIButton:
-(IBAction)doCalculations:(id)sender {
// save the data input
double input1 = [input1Field.text doubleValue];
double input2 = [input2Field.text doubleValue];
double input3 = [input3Field.text doubleValue];
// do the calculations
int i;
for (i = 0; i < [calcNames count]; i++) {
if (selectedCalc == [calcNames objectAtIndex:i]) {
// do calculations here
double numResult = ??????
// if selectedCalc is "first", I want it to do firstCalc(input 1, input 2, input 3)
// if selectedCalc is "second", I want it to do secondCalc(input 1, input 2, input 3), and so on
// the rest is just for displaying the result
NSString* result = [NSString stringWithFormat:#"The answer is %f", numResult];
[resultLabel setText:result];
}
}
}
So basically, it runs a for loop until it finds which calculator is selected from the UIPickerView and when it finds it, runs the calculations and displays them.
I've been trying to understand if maybe function pointers or selectors (NSSelectorFromString?) are the right things to use here and how to use them, but I'm really struggling to understand where to go after a couple days of reading Apple's documentation, Stack Overflow questions, playing with sample code, and tinkering with my own code.
Sorry if the question is too lengthy, I thought it may be more helpful to others looking for assistance in the future to see the full idea. (At least I know sometimes I'm lost with these question pages.)
I would be very grateful for any assistance,
Ryan
You can dynamically invoke a method using a selector. You could for example have a secondary array to calcNames with selector called calcSelectors:
SEL calcSelectors[] = (SEL[3]){
#selector(first:arg:),
#selector(second:arg:),
#selector(third:arg:)};
Calling the right method would then be as simple as:
[self performSelector:calcSelectors[calcIndex] withObject:arg1 withObject:arg2];
If you need more then 2 arguments, then you also need to mess a bit with a NSInvocation instance to setup the call.
Example 1:
NSString *method=[calcNames objectAtIndex:0];//here play with objectatindex
SEL s=NSSelectorFromString(method);
[self performSelector:s];
which will call this method
-(void)first{
NSLog(#"first");
}
-----------------------------------------
Example 2:
NSString *totalMethodName;
totalMethodName=#"vijay";
totalMethodName=[totalMethodName stringByAppendingString:#"With"];
totalMethodName=[totalMethodName stringByAppendingString:#"Apple"];
SEL s=NSSelectorFromString(totalMethodName);
[self performSelector:s];
will call
-(void)vijayWithApple{
NSLog(#"vijayWithApple called");
}
You can make use of NSInvocation to dynamically bind multiple arguments to a selector. Follow this post to learn it.
If you are going to use NSInvocation you have to define your methods in the objective-C way something like the following.
- (double)firstCalcWithInput1:(double)input1 input2:(double)input2 andInput3:(double)input3;
- (double)secondCalcWithInput1:(double)input1 input2:(double)input2 andInput3:(double)input3;

Subtract one from integer displayed in UILabel

I have a UILabel that adds one to its value -- basically it counts up -- when a button is pressed. Could someone please help me with a minus button? That way if the user accidentally presses the add button more than they needed, they can subtract their mistake. I've tried this, but the label's text is set to -1 now. and I want it to just subtract one each time its pressed:
- (IBAction)subtractButton:(id)sender {
static int integerSaved;
integerSaved = integer;
integerSaved -= 1;
[label2 setText:[NSString stringWithFormat:#"%i", integerSaved]];
}
Try this:
- (IBAction)subtractButton:(id)sender {
[label2 setText:[NSString stringWithFormat:#"%d",[label2.text intValue] - 1]];
}
-(void)subtract
{
label2.text = [NSString stringWithFormat:#"%d", [label2.text intValue]-1];
}
This code assumes that you are not using Interface Builder, and that you are manually linking "subtract" to the UIButton. If you are using Interface Builder, try this code.
-(IBAction)subtract:(id)sender
{
label2.text = [NSString stringWithFormat:#"%d", [label2.text intValue]-1];
}
I have not tested this but I think it should work. Good luck!
Using the value of the UIView instance to do arithmetic is not the MVC-way. You should really be separating your data model from your view.
Expose an int, NSInteger or NSNumber property in a class somewhere, where that class is dedicated to holding data values for your app.
When a touch event comes in for a given button, increment the data property and fire a notification that updates the view based on what's in the property. Or add an observer to the property. The observer then updates the view when the property value changes.
Following the MVC pattern would be a more "Apple"-ish or "iOS"-ish way of doing things, than getting the UIView's value, converting it to an integer, and then converting it back to a string.

How to click a checkbox in nstableview and update an object using KVC?

I am trying to learn cocoa and have a few problems with KVC and bindings. I have a nstableview with three columns; "checkbox", "text", "icon". The values of each column is binded to an arraycontroller using KVC. When program is launched the rows and columns are correctly filled into the tableview according to the values in the array. I can click a row and correctly print the content of that row using something like this:
- (IBAction)fileTableViewSelected:(id)sender{
NSInteger r;
NSDate *fModOne;
id object;
r = [[NSNumber numberWithInt:[sender selectedRow]] intValue];
object = [arrayIntersect objectAtIndex:r];
fModOne = [object valueForKey:#"fileModifiedDirOne"];
NSLog(#"Date found in row is %#",fModOne);
}
My problem is when I try to click the checkbox in column one and change the value of the box. Initially, the value of the checkbox is set to 1 using the arraycontroller which works fine, but when I want to change the value of the checkbox of a specific row to 0 by clicking on it the program crashes. When the box is clicked an action is correctly called and this is where I thought I could simply change the value of my objects BOOL by calling:
[object setValue:[NSNumber numberWithBool:NO] forKey:#"doSync"];
My setters and getters for the BOOL doSync is defined as:
#property(nonatomic, readwrite) BOOL doSync;
#dynamic doSync;
- (void)setDoSync:(BOOL) value{
NSLog(#"setting dosync %i", value);
doSync = NO;
}
- (BOOL)doSync{
return doSync;
}
I have searched everywhere for a solution to my problem, but I am unable to find any examples of how to use checkboxes in tableview using KVC and bindings. I appreciate any help I can get on this and I would appreciate any examples I could take a look at.
Cheers and thanks! Trond
You don't need to implement this yourself as an action. Just bind the column through your array controller's arrangedObjects to the doSync property of the model objects.
If you don't want to use Bindings, you still shouldn't implement it as an action. Instead, be the table view's data source and respond to the message the table view will send you to change one of the values.
#dynamic doSync;
There's no reason to have this if you turn around and implement the accessors for that property in the same class.
If this is a managed-object class and the property is an attribute of the entity, then your accessors should send [self willAccessValueforKey:] before and [self didAccessValueForKey:] after accessing the instance variable. If that's all they do, then you should not implement the custom accessors at all; cut them out and have #dynamic alone.
- (void)setDoSync:(BOOL) value{
doSync = NO;
That's not setting the property to the value passed in.