开发者

Trouble in Simple app for iOS

I have a problem. I have 2 classes "Rating" (with .h and .m), "RatingViewController" (with .h and .m).

Rating.h

开发者_如何学编程
#import 
@interface Rating : NSObject {
    int usrLyrics;
    int usrMusic;
    int usrTotal;
}
- (void) setUsrTotal;
@end

Rating.m

#import "Rating.h"
@implementation Rating
-(void) incUsrLyrics
{
    usrLyrics = 5;
}
- (void) incUsrMusic {
    usrMusic = 6;
}
- (void) setUsrTotal {
    usrTotal = usrMusic + usrLyrics;
}
}
@end

RatingViewController.h

@interface RatingItudeViewController : UIViewController {
    Rating *rating;
}
- (IBAction) submitRating;

RatingViewController.m

#import "RatingItudeViewController.h"

@implementation RatingItudeViewController

- (IBAction) submitRating {
    [rating setUsrTotal];
    NSLog(@"usrTotal is %i", [rating usrTotal]);
}
@end

It's looks simple, but doesn't work, in Console always "usrTotal is 0". Help me please.

UPDATED

Just now, I add couple lines in RatingViewController.m

- (IBAction) submitRating {
    [rating incUsrMusic];
    [rating incUsrLyrics];
    [rating setUsrTotal];
    NSLog(@"usrTotal is %d", [rating usrTotal]);
}

and in Rating.h

-(void) incUsrLyrics;
- (void) incUsrMusic;
- (void) setUsrTotal;
- (int) usrTotal;

And when a press a button, in console again "usrTotal is 0".


That is correct, you need to put initialization of usrMusic and usrLyrics variables into init constructor message. By default they are assigned values of 0. 0+0 is 0, hence the result.


The methods incUsrLyrics and incUsrMusic don't ever get called anywhere, thus never setting their initial values. If these values are essential to the operation of the class then they should be established in that class's initializer.

In Rating.m

- (id)init
{
    if (self = [super init])
    {
        usrLyrics = 5;
        usrMusic = 6;
    }

    return self;
}

or better yet, a more specific initializer...

- (id)initWithUserLyrics:(NSInteger)lyricsValue music:(NSInteger)musicValue
{
    if (self = [super init])
    {
        usrLyrics = lyricsValue;
        usrMusic = musicValue;
    }

    return self;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜