When I try adding an "if" statement to my word generator I get an error stating "Expected Expression". If I take the if statement out, it works fine but what I want to do is have several word generators and depending on the value of my variable "variable" determine which word generator is accessed.
Example: If "variable" is equal to 1 then the first word generator is accessed. If "variable is equal to 2 then the second word generator is accessed
Below is the code from my implementation file.
#import "ViewController2.h"
#import "ViewController.h"
#import "ViewController3.h"
#interface ViewController2 ()
#end
#implementation ViewController2
-(IBAction)random {
if (int variable = 3) {
int text = rand() %3;
switch (text) {
case 0:
introLabel.text = #"Test 1";
break;
case 1:
introLabel.text = #"Test 2";
break;
case 2:
introLabel.text = #"Test 3";
break;
default:
break;
}
}
}
-(IBAction)backButton:(id)sender {
ViewController *viewController2 = [[ViewController alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:viewController2 animated:YES];
}
-(IBAction)moreButton:(id)sender {
ViewController3 *viewController2 = [[ViewController3 alloc] initWithNibName:nil bundle:nil];
[self presentModalViewController:viewController2 animated:YES];
}
Thanks in advance for any help.
Your question is unclear but I think you are talking about the line:
if (int variable = 3) {
That is invalid Objective-C syntax. Perhaps you want:
if (variable == 3) {
This assumes you have an instance variable named variable (which is a terrible name).
So your random method becomes something like:
-(IBAction)random {
if (variable == 1) {
int text = rand() %3;
switch (text) {
case 0:
introLabel.text = #"Test 1";
break;
case 1:
introLabel.text = #"Test 2";
break;
case 2:
introLabel.text = #"Test 3";
break;
default:
break;
}
} else if (variable == 2) {
// process the 2nd word generator here
} else if (variable == 3) {
// process the 3rd word generator here
}
}
Again, you need to add an instance variable named variable and you set that value somewhere appropriate. Or variable can be another local variable assigned the value of rand() like you do with the text variable.
Related
I have a custom cell.In that custom cell,there is a textfield and a label.I actually have made a form using custom cell.The user will enter its name,city,state,country,dob detail in that textfield.Now ,on a click of a button I want to save all this data together in a dictionary.But I am not able to understand that how can I save data for different keys using the same textfield as it is being reused.Please help with some code in objective c.Thanks in advance!
I am giving you idea, so that you can implement it
Just take a Macro, like this #define textFieldTag 1000
You are re-using the textfField right. So, in cellForRowAtIndexPath (if u r using table view) set the tag of the textField like this: cell.textType.tag = indexPath.row + textFieldTag;
then
access the textField using delegate
- (void)textFieldDidEndEditing:(UITextField *)textField {
switch (textField.tag - textFieldTag) {
case 0:{
NSString *name = textField.text;
//Take a NSMutableDictionary and add the values over here
break;
}
case 1:
{
NSString *city = textField.text;
break;
}
case 2:
{
NSString *state = textField.text;
break;
}
case 3:
{
NSString *country = textField.text;
break;
}
case 4:
{
NSString *dob = textField.text;
break;
}
default:
break;
}
}
And one thing, when you click the save or what ever button u r using to submit the form remember to dismiss the keyboard [textField resignFirstResponder];, otherwise the last value can be nil.
Thank you
I got this code from ObjC. I want to convert it to Swift, however, I am having difficulties doing so...
ObjC code :
navgivet.h
typedef NS_ENUM(NSInteger, BB3Photo) {
kirkenType = 10 ,
festenType = 20 ,
praestType = 30
};
#property (nonatomic, assign) BB3Photo selectedPhotoType;
navgivet.m
- (IBAction)changeImage:(id)sender {
if ([sender isKindOfClass:[UIButton class]]) {
UIButton *button = sender;
_selectedPhotoType = button.tag;
}
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:#"Vælg Billed"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:#"Vælg fra Biblioteket", #"Vælg Kamera", nil];
sheet.actionSheetStyle = UIActionSheetStyleDefault;
[sheet showInView:[self.view window]];
}
switch (_selectedPhotoType) {
case kirkenType: {
}break;
case festenType: {
}break;
case praestType: {
}break;
default:
break;
Here's my swift code in this attempt
enum BBPhoto1: Int {
case kommunen = 10
case sagsbehandler = 20
case festen = 30
}
#IBAction func changeImage(sender: AnyObject){
if sender .isKindOfClass(UIButton){
let button: UIButton = sender as UIButton
selectedPhoto = BBPhoto1.fromRaw(button.tag)
}
let actionSheet = UIActionSheet(title: "Billeder", delegate: self, cancelButtonTitle: nil, destructiveButtonTitle: nil, otherButtonTitles: "Vælg fra Biblioteket", "Vælg Kamera")
actionSheet.showInView(self.view)
}
var selectedPhoto: BBPhoto1?
switch (selectedPhoto) {
case kommunen {
}
case sagsbehandler{
}
}
but I get errors : "Use of unresolved identifier kommunen" and same messege but with Sagsbehandler.
How do I make it work ?
There are 3 problems in your code.
The first is that selectedPhoto is declared as optional, so you must unwrap it before using in a switch statement - for example using optional binding.
The second problem is that the syntax you're using is incorrect. In each case you have to specify the full name (including the type), followed by a colon:
case BBPhoto1.kommunen:
// statements
but since the type can be inferred by the variable type used in the switch, you can ignore the enum type, but not the dot:
case .kommunen:
// statements
Last, in swift a switch statements require that all cases are handled either explicitly (3 in your case) or using a default case covering all cases non explicitly handled in the switch.
A working version of your code would look like:
enum BBPhoto1: Int {
case kommunen = 10
case sagsbehandler = 20
case festen = 30
}
var selectedPhoto: BBPhoto1?
if let selectedPhoto = selectedPhoto {
switch (selectedPhoto) {
case .kommunen:
println(selectedPhoto.toRaw())
case .sagsbehandler:
println(selectedPhoto.toRaw())
default:
println("none")
}
}
Note that, differently from other languages, the code in each case doesn't automatically fallthrough to the next case, so the break statement is not required - the only use case for it is when a case has no statement (a case with no statement is an error in swift), and in that case the break just acts as a placeholder and its meaning is 'do nothing'.
Suggested reading: Conditional Statements
I am a beginner. And I was trying to transform arabic numbers to ordinal numbers by having the following class.
num is NSInteger, while, during the calculation, the warning pop out "local declaration of '' hides instance"
#import "ordinalNumberFormatter.h"
#implementation ordinalNumberFormatter
- (NSString*)ordinalNumberFormatter:(NSInteger)num
{
NSString *ending;
int ones = num % 10; //Warning came out
int tens = floor(num / 10); //Warning came out
tens = tens % 10;
if(tens == 1){
ending = #"th";
}else {
switch (ones) {
case 1:
ending = #"st";
break;
case 2:
ending = #"nd";
break;
case 3:
ending = #"rd";
break;
default:
ending = #"th";
break;
}
}
return [NSString stringWithFormat:#"%d%#", (int)num, ending]; //Warning came out
}
#end
Do you have a class variable called "num" as well? The warning is just saying that you're using the local variable "num" defined in
- (NSString*)ordinalNumberFormatter:(NSInteger)num
And you might instead want to use the "num" defined as the class variable. Maybe change the above "num" to another name and use that name in the method. That'll clear it all up
Very basic question, but I have an error in my code that can only be answered by one assumption: my class isn't being instantiated!
I haven't written much in Objective C in some time, and I was never really good, so please point out even the most painfully obvious.
I am using:
ObjectSelectionViewController *length = [[ObjectSelectionViewController alloc] initWithMeasureType:0];
ObjectSelectionViewController *mass = [[ObjectSelectionViewController alloc] initWithMeasureType:1];
ObjectSelectionViewController *volume = [[ObjectSelectionViewController alloc] initWithMeasureType:2];
NSLog(#"%#", [length measurementType]);
NSLog(#"%#", [mass measurementType]);
NSLog(#"%#", [volume measurementType]);
The NSLogs return whichever measurement was assigned last, regardless of the separate allocs and inits.
Here is the constructor of the ObjectSelectionViewController class:
#import "ObjectSelectionViewController.h"
#implementation ObjectSelectionViewController
NSString *measurementType;
-(ObjectSelectionViewController*) initWithMeasureType:(int)value
{
switch (value) {
case 0: // Length
measureType = #"Length";
break;
case 1: // Mass
measureType = #"Mass";
break;
case 2: // Volume
measureType = #"Volume";
break;
}
return self;
}
-(NSString*) measurementType
{
return measureType;
}
Thanks for the help, it's driving me crazy!
You need to make measureType an instance variable, so that each object of this type that you create has its own copy:
#interface ObjectSelectionViewController : NSViewController {
NSString * measureType; // Declare an NSString instance variable
}
- (id) initWithMeasureType: (int)value;
#end
As it is, there is only one copy of the variable, and every time you instantiate a new object, its value changes. Since each instance is referring to the same copy, they all get the same value:
ObjectSelectionViewController *length = [[ObjectSelectionViewController alloc] initWithMeasureType:0];
NSLog(#"%#", [length measurementType]); // Prints "Length"
ObjectSelectionViewController *mass = [[ObjectSelectionViewController alloc] initWithMeasureType:1];
NSLog(#"%#", [length measurementType]); // Prints "Mass"
You also need to change your init... method as mentioned by other answerers:
- (id) initWithMeasureType: (int)value {
// Call superclass's initializer
self = [super init];
if( !self ) return nil;
switch (value) {
case 0: // Length
measureType = #"Length";
break;
case 1: // Mass
measureType = #"Mass";
break;
case 2: // Volume
measureType = #"Volume";
break;
}
return self;
}
Since you are assigning a literal string to the instance variable, you do not need to worry about managing its memory; if you were doing anything more complicated, you would probably do well by declaring a property.
Another note: initializer methods should always return id, a generic object pointer, to allow subclasses to work properly.
You need to call [super init] first, like this:
-(id) initWithMeasureType:(int)value
{
if ((self = [super init]))
{
switch (value) {
case 0: // Length
measureType = #"Length";
break;
case 1: // Mass
measureType = #"Mass";
break;
case 2: // Volume
measureType = #"Volume";
break;
}
}
return self;
}
Constructors are a convention in Objective-C rather than a language feature. So, for example, there's no automatic calling of parent constructors (just like you wouldn't expect any other overridden method to call its parent implementations). Similarly, the names used for constructors are just conventions, so the compiler knows nothing of init. With that in mind, what you actually want as your constructor is:
-(id) initWithMeasureType:(int)value
{
if((self = [super init]))
{
switch (value) {
case 0: // Length
measureType = #"Length";
break;
case 1: // Mass
measureType = #"Mass";
break;
case 2: // Volume
measureType = #"Volume";
break;
}
}
return self;
}
Assuming measureType is an instance variable (declared as part of the interface, generally speaking) and not a global then that should do what you want.
In your custom init method you just need to start with:
self = [super init];
- (id) initWithMeasureType: (int)value {
// Call superclass's initializer
self = [super init];
if( !self ) return nil;
switch (value) {
case 0: // Length
measureType = #"Length";
break;
case 1: // Mass
measureType = #"Mass";
break;
case 2: // Volume
measureType = #"Volume";
break;
}
return self;
}
I want to get the name of a sender in Objective-C. For example, below I have a method which is called by an instance of UISlider in Interface Builder, I want to know what the instance name of it is so I can later add conditional blocks to the method for which instance of UISlider called the method.
e.g.
-(IBAction)sliderChanged:(UISlider *)sender {
//labAt1TimeRequired.text = [NSString stringWithFormat:#"%.1f", [sender value]];
NSLog(#"%#",sender);
Outputs:2010-10-15 22:46:02.257 EPC[3225:207] <UISlider: 0x495b140; frame = (205 3; 118 23); opaque = NO; autoresize = RM+BM; layer = <CALayer: 0x492e340>>
I want to be able to say
if(sender==myInstanceName) {
//do this
}
You could use
.tag member
to read an write and integer ID for the slider like this:
-(IBAction)sliderChanged:(UISlider
*)sender {
switch (sender.tag) {
case 0:
//SLider 0
break;
case 1:
//SLider 1
break;
default:
break;
}
}
Tag ID's can also be set for components in IB.
If your set on a string then you would need to subclass a UISlider.
You would use the tag property of UIView for identifying the sender.
-(IBAction)sliderChanged:(UISlider *)sender {
//labAt1TimeRequired.text = [NSString stringWithFormat:#"%.1f", [sender value]];
if (sender.tag == 1)
{
// do whatever
}
else
{
// do something else
}
}