在viewDidLoad()中调用方法。使用indexPath

时间:2012-03-29 20:20:50

标签: objective-c ios uitableview sdk

我有TableView。我的数据源是SQLite数据库。我正在尝试为numberOfRowsInSection:方法的一些消息(我知道消息ID和它的文本)计算一些注释。

-(NSInteger)numberOfCommentsForMessage:(NSIndexPath *)indexPath {
    MDAppDelegate *appDelegate = (MDAppDelegate *)[[UIApplication sharedApplication] delegate];
    Comments *comment = (Comments *)[appDelegate.comments objectAtIndex:indexPath.row];
    if (MessageID == [comment.messageID integerValue]) {
        numberOfCommentsForMessage++;
     }
    NSLog(@"number of comments = %i",numberOfCommentsForMessage);
    return numberOfCommentsForMessage;
}

即使是NSLog也不行。我认为应该在viewDidLoad()中调用此方法,但不确定这种方法是否正确。

修改

Comments.h

@interface Comments : NSObject {
    NSString *messageID;
    NSString *commentText;
}

@property (nonatomic, retain) NSString *messageID;
@property (nonatomic, retain) NSString *commentText;

-(id)initWithName:(NSString *)mID commentText:(NSString *)cText;

MessageID我从上一个视图中得到:

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
          MessageText:(NSString *)messageText
          MessageDate:(NSString *)messageDate
            MessageID:(NSInteger)messageID;
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        MessageText = [NSString stringWithString:messageText];
        MessageDate = [NSString stringWithString:messageDate];
        MessageID = messageID;
    }
    return self;
}

1 个答案:

答案 0 :(得分:1)

确切地知道哪些不起作用也很有趣。您的应用程序是在NSLog崩溃还是返回错误的消息计数?

由于您从方法返回numberOfCommentsForMessage,因此需要将numberOfCommentsForMessage的范围缩小到方法中的局部变量。

-(NSInteger)numberOfCommentsForMessage:(NSIndexPath *)indexPath {
    NSInteger numberOfComments = 0;
    MDAppDelegate *appDelegate = (MDAppDelegate *)[[UIApplication sharedApplication] delegate];
    Comments *comment = (Comments *)[appDelegate.comments objectAtIndex:indexPath.row];
    if (MessageID == [comment.messageID integerValue]) {
        numberOfComments++;
     }
    NSLog(@"number of comments = %d",numberOfComments);
    return numberOfComments;
}