Reputation: 3
I am very new to objective-c and having a problem to initialize an object in view controller. The problem I am having is that when setTemp method is called, "0" is printed on the screen instead of the value of cTemp I would like it to be. Can anyone help me on this problem?
Below are excerpts of the code I have.
SJT.h
#import <Foundation/Foundation.h>
#import <stdlib.h>
@interface SJT : NSObject {
int cTemp;
}
- (int) newTemp;
@end
SJT.m
#import "SJT.h"
@implementation SJT
- (int) newTemp
{
cTemp = 25 + rand() % 8;
return cTemp;
}
@end
SJTViewController.h
#import <UIKit/UIKit.h>
@class SJT;
@interface SJTViewController : UIViewController {
IBOutlet UILabel *temp;
SJT *sjt;
}
@property (retain, nonatomic) UILabel *temp;
@property (retain, nonatomic) SJT *sjt;
- (IBAction) setTemp: (id) sender;
@end
SJTViewController.m
#import "SJTViewController.h"
#import "SJT.h"
@implementation SJTViewController
@synthesize temp;
@synthesize sjt;
- (IBAction) setTemp: (id) sender
{
NSString *tempText = [[NSString alloc] initWithFormat:@"%d",sjt.newTemp];
temp.text = tempText;
[tempText release];
}
.
.
.
@end
Upvotes: 0
Views: 541
Reputation: 28864
Both Jacob and teabot have pointed out valid possible reasons -- which one is correct (or both!) depends on pieces of code we can't see in your post.
Based on what you've written so far, you might not be thinking of newTemp
as a property, but more as a function call, so I would suggest changing your code to:
- (IBAction) setTemp: (id) sender {
int tempInt = [self.sjt newTemp];
self.temp.text = [NSString stringWithFormat:@"%d", tempInt];
}
which is functionally equivalent. Note the convenience constructor stringWithFormat:
returns an autoreleased object, which is then retained by the retain
property text
of the temp
UILabel
.
The other thing to double-check in your code is that self.sjt
is not nil
, which is exactly what teabot said. Objective-C returns 0 on method calls invoked on a nil
pointer.
Upvotes: 0
Reputation: 1430
The problem is that you're mistaking property syntax for a method call; i.e.
sjt.newTemp
would become a call to [sjt newTemp]. Which happens to be exactly what you want, except that you have not specified in your header/implementation that there actually is a property called newTemp.
So, in this scenario what you want to do is either a) define the property in the header:
@property(nonatomic, readonly) int newTemp;
or b), just call the method newTemp:
[sjt newTemp]
Upvotes: 2
Reputation: 15444
Are you certain that sjt
is not nil
? You don't provide the code where and instance of SJT
is constructed. In Objective-C you can call a method on a nil
reference without error, and if you do so on a method that returns an int
it will return 0
.
So sjt.newTemp
will return 0
if sjt
is nil
.
Upvotes: 0