我有问题。我有2个类“评级”(带.h和.m),“RatingViewController”(带.h和.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
它看起来很简单但不起作用,在Console中总是“usrTotal为0”。 请帮帮我。
已更新
刚才,我在RatingViewController.m
中添加几行- (IBAction) submitRating { [rating incUsrMusic]; [rating incUsrLyrics]; [rating setUsrTotal]; NSLog(@"usrTotal is %d", [rating usrTotal]); }
并在Rating.h中
-(void) incUsrLyrics; - (void) incUsrMusic; - (void) setUsrTotal; - (int) usrTotal;
当按下按钮时,再次在控制台中“usrTotal为0”。
答案 0 :(得分:1)
这是正确的,您需要将 usrMusic 和 usrLyrics 变量的初始化放入 init 构造函数消息中。默认情况下,它们被赋值为0. 0 + 0为0,因此得到结果。
答案 1 :(得分:1)
方法incUsrLyrics
和incUsrMusic
不会在任何地方被调用,因此永远不会设置它们的初始值。如果这些值对于类的操作是必不可少的,那么它们应该在该类的初始化器中建立。
在Rating.m
- (id)init
{
if (self = [super init])
{
usrLyrics = 5;
usrMusic = 6;
}
return self;
}
或更好,更具体的初始化程序......
- (id)initWithUserLyrics:(NSInteger)lyricsValue music:(NSInteger)musicValue
{
if (self = [super init])
{
usrLyrics = lyricsValue;
usrMusic = musicValue;
}
return self;
}