【发布时间】:2015-12-28 22:56:53
【问题描述】:
我正在尝试创建一个购物清单应用。我对 Objective-C 很陌生。不知何故,这段代码不起作用,我不知道我做错了什么。每当我在文本字段中输入内容并单击添加时,文本都不会添加到表格视图中。
头文件:
@interface NotesViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) NSMutableArray *notes;
@property (nonatomic, strong) IBOutlet UITextField *noteTitleText;
@property (nonatomic, strong) IBOutlet UITableView *noteBlockTableView;
@end
实现文件:
@implementation NotesViewController
@synthesize notes; @synthesize noteTitleText; @synthesize noteBlockTableView;
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [notes count]; }
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *tableViewTitle;
tableViewTitle = [notes objectAtIndex:[indexPath row]];
UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
[[cell textLabel] setText:[tableViewTitle objectForKey:@"cellTitle"]];
return cell;
}
-(IBAction)addNote {
NSDictionary *tableViewTitle;
tableViewTitle = [[NSDictionary alloc] initWithObjectsAndKeys:[noteTitleText text], @"cellTitle", nil];
[notes addObject:tableViewTitle];
[noteBlockTableView reloadData];
noteTitleText.text = @"";
}
【问题讨论】:
-
您是否在某处(通常在
init或viewDidLoad)初始化notes(到一个空的可变数组)? -
此外,在现代 Objective-C 中,您不需要合成属性,这是自动完成的,您可能希望使用字典文字 (
@{@"cellTitle": noteTitleText.text}) 和访问器 (tableViewTitle[@"cellTitle"])。更好的是,您应该为此使用一个新类而不是字典。 -
而且你不应该分配
UITableViewCells,你应该使用dequeueReusableCellWithIdentifier:forIndexPath:
标签: ios objective-c uitableview tableview