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

问题描述:

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

-(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; 

邮件ID我以前的观点得到:

- (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; 
} 
+0

我们需要比这更多的代码。请发布MessageID的定义,以及您的Comments.h头文件。 – Sam 2012-03-29 20:28:09

+0

但是你从哪里调用'numberOfCommentsForMessage:'从现在开始?它是否被称为? – 2012-03-29 21:05:43

+0

如果你多次调用它,你会不断增加计数器,如果你有10条评论,你的numberOfCommentsForMessage将是第一次,然后是20,然后是30等等。这就是为什么你应该使用局部变量你的方法,而不是一个实例变量,看到我的帖子。 – 2012-03-30 07:34:02

这也将是有趣的,确切地知道什么是不工作。你的应用程序是否在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; 
} 
+0

应用程序不会崩溃。我认为这种方法根本不会调用。但为什么'numberOfCommentsForMessage'不能是局部变量?即使我合成它? – RomanHouse 2012-03-29 21:10:07

+0

由于您既返回值又增加实例变量,看起来像一个错误和/或反模式。 如果它没有崩溃,您发现错误的是什么? – 2012-03-30 07:32:32

+0

任何错误,任何其他错误。可能这种方法根本不叫。这就是为什么我问如何在viewDidLoad中调用它。 – RomanHouse 2012-03-31 10:07:18