开发者

Class method (NSString type) called from viewcontroller returns nil?

I'm a c++ programmer new to objective-c.

I created a calculator app that is working fine using a single view. I开发者_Python百科 have a Calculations class and a ViewController. Every time a button is pressed, an IBAction method in the ViewController calls methods defined in the Calculations class to handle the input and returns the output as an NSString which I then set as the value of the label.text field.

Now I am working on a tab bar app using the same Calculations class. This app has two tabs, each with a unique set of input buttons for the calculator (both views sharing the same input/output data). The first tab is identical to my first app with the single view, so I am trying to do this in a similar fashion.

Here is the problem:

When a button is pressed, the IBAction method that handles the input runs through the calls to the Calculations class methods (shown below) without error:

-(IBAction)readInput:(id)sender {    
    [_calculations input:[sender titleForState:UIControlStateNormal]];
    inputField.text = [_calculations inputDisplay];
    outputField.text = [_calculations outputDisplay];
}

however, both the inputDisplay and outputDisplay methods return nil. Using the debugger I noticed that I am unable to "step into" the calls to _calculations methods, instead the line is skipped and the value returned by both is nil. I added the following method:

-(IBAction)setNumber:(id)sender {
    NSString *button =(NSString *)[sender titleForState:UIControlStateNormal];
    inputField.text = button;
}

and if I attach this to the input buttons I can see the display updated. This seems to be an issue with calling the _calculations member functions and tab bar views (because this issue is not present using a single view).

I realize that I left out a lot of information, but I did it to avoid providing irrelevant information. I will provide all details that are necessary if asked.


Check to make sure _calculations is not nil.

You can send any message (call any method) on nil and it will just return nil, not cause an exception.


Without seeing more code it is going to be a bit difficult to diagnose.

If I was trying to debug this issue I would first make sure _calculations points to the object you want it to point to. If its loaded from a NIB then it might not be getting initialised, and still be nil. You can send messages to nil objects without any issues. If an object receives a message that it cant handle (the method doesn't exist, or the target object is nil) then the return for that call will be nil.

I have in the past put initilization code into the init: method, and spent a few hours why it wasn't being called, until it dawned on me that I needed to put my init code into the viewDidLoad:, or the initWithNibName:bundle: or even the initWithCoder: selector.

HTH, Matt

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜