Declare typedef struct Variable - ios

I have this typedef in my .h file
typedef struct
{
NSInteger openTime;
NSInteger closeTime;
} ShopHours;
Now I want to declare it in my .m file and then like you would a NSString that you want to use throughout the .m.
SO basically I want to initialize it, as an array of the typedef and then so I can assign it a vaule in my viewDidLoad method, as I see fit.
So basically I want to declare it like
ShopHours weekSchedule[] = {};
And then in viewDidLoad
weekSchedule[] = {//my data}
But when I try to declare and use it like this I get compile error
Field has incomplete type 'SHopHours[]'
Thanks for the help in advance

The compiler needs to know how big the weekSchedule variable is in order to put some memory aside for it. You could declare it as shopHours weekSchedule[7] for example.

I tried, the problem was you need to decleare the size of the array first :
#interface LoginScreen (){
ShopHours aa[5];
}
- (void)viewDidLoad
{
[super viewDidLoad];
for (int i = 0; i < 5; i++) {
aa[i].closeTime = 5+i;
aa[i].openTime = 10 + i;
}
}
In another method I logged it:
for (int i = 0; i < 5; i++) {
NSLog(#"Open Time %ld\n",(long)aa[i].openTime);
NSLog(#"Close Time %ld\n",(long)aa[i].closeTime);
}
Works just fine.
If you want dynamic memory allocation,you can do it
#interface LoginScreen (){
ShopHours *aa;
}
- (void)viewDidLoad
{
[super viewDidLoad];
aa = malloc(sizeof(ShopHours) * 5);
for (int i = 0; i < 5; i++) {
aa[i].closeTime = 5+i;
aa[i].openTime = 10 + i;
}
}
Hope this helops.. :)

Related

isEqual is not working properly in xcode

My code looks like proper but isEqual used to compare two object is not working. i'm new to iOS. there is no much resource to check. [box2 isEqual:box1] is always gives me No. but it supposed to give Yes. anything wrong in my code, please suggest me the correct thing. thanks in advance. expecting best suggestion .
#import <Foundation/Foundation.h>
#interface Box:NSObject
{
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
}
#property(nonatomic, readwrite) double height; // Property
-(double) volume;
//-(id)initWithLength:(double)l andBreadth:(double)b;
#end
#implementation Box
#synthesize height;
-(id)init
{
self = [super init];
if(self)
{
length = 2.0;
breadth = 3.0;
}
return self;
}
-(double) volume
{
return length*breadth*height;
}
#end
#class Box;
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
Box *box1 = [[Box alloc]init]; // Create box1 object of type Box
Box *box2 = [[Box alloc]init];
NSLog (#"hello world");
box1.height = 5.0;
NSLog (#"%ld",[box1 volume]);
if([box2 isEqual:box1])
{
NSLog(#"%b",[box2 isEqual:box1]);
}
[pool drain];
return 0;
}
You have to override isEqual method in your object.
e.g. in your "#implementation Box"
- (BOOL)isEqual:(id)object
{
if ([object isKindOfClass:[Box class]]) {
Box*box = (Box*)object;
return self.height == box.height; // compare heights values
}
return [super isEqual:object];
}
isEqual: works just fine and as documented, but not as you expected.
isEqual: is a property of NSObject. It returns YES if two object pointers are the same, and NO if they are not. If you want a different result, you need to override isEqual for your Box class. Note that the argument to isEqual: could be anything, not just a Box, so you need to be careful.
Obviously you shouldn't declare instance variables put properties, so the code below assumes that. The way your code is written, you will have some confusion with an instance variable height, a property height, and an instance variable _height, which will give you headaches. It also assumes that you are not subclassing Box (for example you could have a coloured box, which should not be equal to a Box with same width, height and breadth).
- (BOOL)isEqual:(id)other
{
if (! [other isKindOfClass:[Box class]]) return NO;
Box* otherBox = other;
return _length == other.length && _breadth == other.breadth
&& _height == other.height;
}

Array value not displaying in iOS simulator

I am making a simple calculator application that displays the equation that the user has inputed and also the output of the equation. At the top of my header file I created three integers and an array...
#import <UIKit/UIKit.h>
int Method;
int SelectNumber;
float RunningTotal;
NSMutableArray *Equation;
#interface SecondCalculatorViewController : UIViewController{
IBOutlet UILabel *EquationLabel;
IBOutlet UILabel *ResultLabel;
}
- (IBAction)OneButton:(id)sender;
- (IBAction)TwoButton:(id)sender;
- (IBAction)ThreeButton:(id)sender;
- (IBAction)FourButton:(id)sender;
- (IBAction)FiveButton:(id)sender;
- (IBAction)SixButton:(id)sender;
- (IBAction)SevenButton:(id)sender;
- (IBAction)EightButton:(id)sender;
- (IBAction)NineButton:(id)sender;
- (IBAction)ZeroButton:(id)sender;
- (IBAction)Plusbutton:(id)sender;
- (IBAction)MinusButton:(id)sender;
- (IBAction)MultiplyButton:(id)sender;
- (IBAction)DivideButton:(id)sender;
- (IBAction)CalculateButton:(id)sender;
- (IBAction)ClearButton:(id)sender;
#end
In my implementation, I prepare each input to be displayed in a label and then also I try to save SelectNumber into the first index in the array I created. I then try to display it in the label. Here is an example of one of the buttons...
- (IBAction)OneButton:(id)sender {
//[Equation addObject:0];
SelectNumber = SelectNumber * 10;
SelectNumber = SelectNumber + 1;
//EquationLabel.text = [NSString stringWithFormat:#"%i",SelectNumber];
[Equation replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:#"%i",SelectNumber]];
EquationLabel.text = [Equation objectAtIndex:0];
}
When I run this in the simulator and push any number, it does not display the first value in the array "Equation".
How can I fix this?
It seems that Equation is not initialized. You need to initialize it:
Equation = [NSMutableArray new];
// or Equation = [[NSMutableArray alloc] init];
viewDidLoad method could be a good place for this code in your case.

UIPickerView that worked in iOS 6.1 now crashes in Xcode 5

I developed an app for iOS 6 that called a UIPickerView. Now that I upgraded to Xcode 5, the app works fine for iOS 7, but no longer for iOS 6.
The app crashes when it segues to the pickerview.The pickerview has 1 component and 10 rows.
The header file is below:
#import <UIKit/UIKit.h>
#import "ViewController.h"
#interface DxChooserViewController : UIViewController <UIPickerViewDataSource, UIPickerViewDelegate>
#property (weak, nonatomic) id delegate;
#property (weak, nonatomic) IBOutlet UIPickerView *ptDxPicker;
- (IBAction)dismissDxChooser:(id)sender;
#end
And pertinent sections of the implementation:
#import "DxChooserViewController.h"
...
#implementation DxChooserViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
_dxNames=#[#"NILM (Negative Pap)",#"ASC-US",#"LSIL",#"ASC-H",#"HSIL",#"AGC",#"Atypical Endometrial Cells",#"Atypical Endocervical Cells",#"AIS (adenocarcinoma in situ)",#"Unsatisfactory Pap"];
NSString *chosenDxString = ((ViewController *)self.presentingViewController).ptDx.text;
int chosenDxInt = 0;
if ([chosenDxString isEqualToString:#""]) {
chosenDxInt = 0;
} else {
chosenDxInt = [_dxNames indexOfObject:(chosenDxString)];
}
[self.ptDxPicker selectRow:(NSInteger)chosenDxInt inComponent:0 animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
ViewController *initialView;
initialView = (ViewController *)self.delegate;
NSString *chosenDxString = ((ViewController *)self.presentingViewController).ptDx.text;
int chosenDxInt = 0;
if ([chosenDxString isEqualToString:#""]) {
chosenDxInt = 0;
} else {
chosenDxInt = [_dxNames indexOfObject:(chosenDxString)];
}
[initialView displayDx:_dxNames[(NSInteger)chosenDxInt]]; // returns default dx if nothing is selected
}
...
#end
Update:
The problem was solved, but here is what the crash was:
2013-12-14 10:47:54.518 Pap Reader[48513:907] * * * Terminating app due to uncaught exception 'NSRangeException', reason: '* * * -[NSMutableIndexSet addIndexesInRange:]: Range {2147483647, 1} exceeds maximum index value of NSNotFound - 1'
One possible source of crash is if the desired chosenDxString was not successfully found in the array (i.e. you should check to make sure that chosenDxInt did not return NSNotFound). You also don't check to make sure that chosenDxString was not nil.
Thus, you might replace:
int chosenDxInt = 0;
if ([chosenDxString isEqualToString:#""]) {
chosenDxInt = 0;
} else {
chosenDxInt = [_dxNames indexOfObject:(chosenDxString)];
}
with:
int chosenDxInt = 0;
if (choseDxString && ![chosenDxString isEqualToString:#""]) {
chosenDxInt = [_dxNames indexOfObject:chosenDxString];
if (chosenDxInt == NSNotFound)
chosenDxInt = 0;
}
You also have a programmatically defined array of values, but you're not showing us the code that specifies the delegate/datasource of the picker view and retrieves those values. So I presume you've set the datasource/delegate properties of the picker view and have implemented methods like:
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
return [self.dxNames count];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return self.dxNames[row];
}
In terms of the specific problem in your case, you must update your question with the details of the crash (the details of the crash, at what line it crashed). If it's not apparent which line you're crashing at (i.e. it's just cryptically referring to your main function), you might also want to turn on exception breakpoints so it highlights the offending line of code when it crashes.

make custom number pad class called by several view controllers

I'm new to objective-c and iOS programming.I want to use a custom number pad for a game input. There are several types of games, (game1 game2 game3) and the games may require more or less numbers to be displayed on the number pad (control).
Each games rules and display properties are written in separate view controller classes. I tried cutting and pasting a copy of the number pad from game1 to the other controllers. It throws an error (at build), saying the name for the number buttons properties that I am using have already been used.
Will this would require me to rename and relink all object and properties for each game. To much maintenance overhead for me. So I have been trying to make a NumPad class, derived from NSObject.
This works fine until I try to create a view/container view from the non view controller class. I instantiate the numpad object in the viewdidload section of the game1 view controller. This is what I have so far.
.h file
#import <Foundation/Foundation.h>
#import "NumberPadTestAppDelegate.h"
#interface NumPad : NSObject
-(void)numberPadSetUp: (int) numberOfButtons;
#end
.m file
#import "NumPad.h"
#implementation NumPad
-(void)numberPadSetUp: (int) numberOfButtons
{
// Instantiate a Container View by code??? test.
CGRect frame = CGRectMake(14, 47, 740, 370);
UIView *Mycontainer = [[UIView alloc] initWithFrame:frame];
Mycontainer.backgroundColor = [UIColor blueColor];
[Mycontainer addSubview:Mycontainer];
// This was here for testing before adding the above four lines.
for (int a = 1; a < numberOfButtons +1; a++)
{
NSLog(#"Button %i has been added.",a);
}
NSLog(#" ");
NSLog(#"Numberpad setup is complete.");
} // End of "numberPadSetUp" routine.
#end
.m file from game1 test controller
#import "NumberPadTestViewController.h"
#interface NumberPadTestViewController ()
#end
#implementation NumberPadTestViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NumPad *MyNumberPad =[[NumPad alloc]init];
[MyNumberPad numberPadSetUp:9];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
This code gives a run time error as written.
int main(int argc, char * argv[])
{
#autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([NumberPadTestAppDelegate class]));
}
}
I was also wondering if using the container view control in IB would accomplish the task or might I get the same naming errors as before?
What am i missing here?
Problem is in this line
[Mycontainer addSubview:Mycontainer];
You are declaring Mycontainer and adding it to itself. You should write class like follow
#import "NumPad.h"
#implementation NumPad
#define kButtonWidth 50
#define kButtonHeight 15
#define kPadding 20
-(void)numberPadSetUp: (int) numberOfButtons
{
// Instantiate a Container View by code??? test.
// This was here for testing before adding the above four lines.
int xPos = 0;
int yPos = 0;
for (int a = 1; a < numberOfButtons +1; a++)
{
UIButton *aButton = [UIButton buttonWithType:UIButtonTypeSystem];
CGRect aButtonFrame = CGRectMake(xPos, yPos, kButtonWidth, kButtonHeight);
aButton.frame = aButtonFrame;
[aButton setTitle:[NSString stringWithFormat:#"%d",a] forState:UIControlStateNormal];
[self addSubview:aButton];
xPos+=kButtonWidth+kPadding;
if(fmod(a, 3)==0){
yPos+=kButtonHeight+kPadding;
xPos = 0;
}
NSLog(#"Button %i has been added.",a);
}
NSLog(#" ");
NSLog(#"Numberpad setup is complete.");
} // End of "numberPadSetUp" routine.
#end
And in your main class
NumPad *MyNumberPad =[[NumPad alloc]initWithFrame:CGRectMake(14, 47, 740, 370)];
[MyNumberPad numberPadSetUp:9];
[self.view addSubview:MyNumberPad];
[self.view bringSubviewToFront:MyNumberPad];
This will give you result like following images in iOS6/iOS7

Clearing/Resetting all string and variables

I have a routine in xcode that calls a function and spits out a result to a UITextView element on an iPhone app.
Before the routine is started I want to reset all NSString objects/values and any variables that I used to calculate the result. Is there a quick way to do this?
So far no matter what I retype in the UITextField it just gets ignored after the initial calculation.
Code for the solve button :-
- (IBAction)Solve:(id)sender {
//
// Reset strings and variable code here
//
[_Number1 resignFirstResponder];
[_Number2 resignFirstResponder];
[_Number3 resignFirstResponder];
[_Number4 resignFirstResponder];
[_Number5 resignFirstResponder];
[_Number6 resignFirstResponder];
[_TargetNum resignFirstResponder];
// Dismiss Keyboard
int numb1,numb2,numb3,numb4,numb5,numb6,numTar;
numb1 = [self.Number1.text intValue];
numb2 = [self.Number2.text intValue];
numb3 = [self.Number3.text intValue];
numb4 = [self.Number4.text intValue];
numb5 = [self.Number5.text intValue];
numb6 = [self.Number6.text intValue];
numTar = [self.TargetNum.text intValue];
mainLoopOne(numb1,numb2,numb3,numb4,numb5,numb6,numTar);
// Start calculation with field values
readAnswers = #"Please read answers bottom-up.\n";
cantCalc = NULL;
finalResult = #"";
if (numb1 != 0) {
int ii;
for(ii = 0; ii < 6 ; ii++) {
if (allAnswers[ii] != NULL) {
finalResult = [finalResult stringByAppendingFormat:#"%#", allAnswers[ii]];
}
}
if (finalResult == NULL) {
cantCalc = #"Unfortunately, that doesn't seem to be possible, as there was no answer calculated.\n";
readAnswers = #"";
}
CompileText = [NSString stringWithFormat:#"%#\n%#\nfrom %d combination tries.", readAnswers, finalResult, countCombi];
[self.TextWin setText:CompileText];
}
countCombi = 0;
}
#end
Most of the strings and variables are set just under the #import "ViewController.h" so they are global :-
NSString *readAnswers;
NSString *cantCalc;
NSString *finalResult;
NSString *allAnswers[10];
NSString *CompileText;
NSString *readAnswers;
NSString *finalResult;
#define DIV 0
#define MUL 1
#define ADD 2
#define SUB 3
int n1,n2,n3,n4,n5,n6;
int answer_counter = 0;
int tar2 = 0;
int number[6];
int target = 0;
int used[6];
int countCombi;
Thanks.
Create a reset method that alloc inits every string in your view controller again. You can set the textview's text to "".
In theory you could write a helper class that you pass in an object (your view controller) and it uses introspection to reset everything that is a string or whatever you want. This is a good approach for modularity and reusability, however it requires knowledge of c, and introspection.
Yes whatever williams say thats correct. Implement like below:
-(IBAction)doClear:sender
{
[Yourtextview setString];
}

Resources