Objective C - Get a class to return a value
I rarely ask questions, but this one is frustrating me as I can not find an answer anywhere!
I just need to call the function in GameChallenges.m and return the value to the view controller. GameChallenges.m will be called by different view controllers, thats why its separate. Please help!
I have a separate class file called GameChallenges.
This has a function/method in it: in the .h
@class StatsViewController;
@interface GameChallenges : NSObject {
StatsViewController* statsController;
NSString* challengeTitle;
}
@property (nonatomic, retain) IBOutlet StatsViewController* statsController;
@property (assign) NSString* challengeTitle;
-(NSString*)checkChallenge:(int)challegeID;
@end
开发者_运维问答
in the .m
#import "GameChallenges.h"
#import "StatsViewController.h"
@implementation GameChallenges
@synthesize challengeTitle,statsController;
-(NSString*)checkChallenge:(int)challegeID{
if(challegeID==1){
self.challengeTitle = @"Some Text.";
return challengeTitle;
}else if(challegeID==2){
self.challengeTitle = @"Some Other Text.";
return challengeTitle;
}
}
From a view controller called StatsViewController I am calling this method
in the .h
@class GameChallenges;
@interface StatsViewController : UIViewController {
UILabel* challengeIDDescText;
}
@property (nonatomic, retain) IBOutlet UILabel* challengeIDDescText;
@property (nonatomic, retain) IBOutlet GameChallenges* challenges;
@end
in the .m
[challenges checkChallenge:tempString];
challengeIDDescText.text = challenges.challengeTitle;
Your code is quite weird, I'd say this is what's happening:
-[GameChallenges checkChallenge]
seems to expect an int
and you call it with a variable called tempString
that I guess is an NSString *
. More likely than not, your method is ending without assigning challengeTitle
and without a valid return
value. Fix it with return nil
as last statement and passing an int
.
This kind of problems are very easy to solve using the debugger.
Also, have a look to Apple samples.
I'm beginner in objective-C, however, code in the GameChallenges.m looks weird to me... Wouldn't this be better?
challengeIDDescText.text = [challenges checkChallenge:challengeId];
精彩评论