未在我的表格视图中显示的数组
问题描述:
我通过将其保存在nsuserdefaults中从另一个视图控制器传递可变数组。然后我在新的视图控制器中检索它,它在nslog中很好。当我的代码达到numberofrowsinsections时遇到问题。看起来像我的tableview不识别我的数组对象。感谢任何帮助,因为我是编码方面的新手。未在我的表格视图中显示的数组
#import "ViewController.h"
#import "RecordView.h"
#import "bookCellTableViewCell.h"
@interface ViewController()
@end
@implementation ViewController
@synthesize arr;
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *arr = [[NSMutableArray alloc]init];
arr = [[NSUserDefaults standardUserDefaults] valueForKey:@"projects"];
NSLog(@"arr%@", [arr description]);
#pragma mark - Table view data source
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arr count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//static NSString *CellIdentifier = @"Cell";
bookCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ToBook"];
if(cell != nil)
{
cell.songTitle.text = [arr objectAtIndex:indexPath.row];
testLabel.text = @"Hello";
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [bookView cellForRowAtIndexPath:indexPath];
}
@end
答
这是一个范围问题:
你已经宣布你的数据源中viewDidLoad
NSMutableArray *arr = [[NSMutableArray alloc]init];
这是不正确的,你的数据源应该是一个属性,或者至少类范围的变量。
您应该初始化它在viewDidLoad
但在类级别上声明它。
看起来你已经有一个名为arr
的属性了,智能编译器应该警告你模糊不清。
为了解决这个问题只是删除了这一行的NSMutableArray *
一部分,就像这样:
arr = [[NSMutableArray alloc]init];
您还滥用NSUserdefault
这并不意味着通过控制器之间的数据,它更适合用于保存基本用户设置值。
要传递数据,只需在提供属性之前设置ViewController
属性的值。
感谢您的帮助,但我无法使其工作。我能够将我的数组传递给下一个Viewcontroller的唯一方法是使用nsuserdefaults或创建一个单例。当使用单例时,我能够nslog数组,这意味着该对象正在被传递,但我现在正在收到“nsdictionary长度无法识别的选择器错误”。 – 2014-10-17 20:03:58
对不起最后的评论,但我的问题已解决,谢谢!这是一个伟大的单身教程http://x-code-tutorials.com/2012/06/04/pass-nsobjects-and-values-between-view-controllers/ – 2014-10-17 20:16:40
@MichaelBain只是告诉我你是如何调用viewController的,我们对此进行分类 – meda 2014-10-17 20:16:51