将现有阵列绑定到tableView IOS
调试时,我有一个包含5项的数组,但当我尝试将它们绑定到tableview时,tableview是空的,没有错误。 如果一个用户手动创建一个数组并初始化WithObjects,但我已经有了一个数组,它就可以工作了 在此之后,我的数组有5个对象将现有阵列绑定到tableView IOS,ios,iphone,objective-c,uitableview,nsarray,Ios,Iphone,Objective C,Uitableview,Nsarray,调试时,我有一个包含5项的数组,但当我尝试将它们绑定到tableview时,tableview是空的,没有错误。 如果一个用户手动创建一个数组并初始化WithObjects,但我已经有了一个数组,它就可以工作了 在此之后,我的数组有5个对象 array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; 问题是我尝试初始化数组的部分 如果
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
问题是我尝试初始化数组的部分
如果我这样做,我的数组在之后是空的
array = [[NSMutableArray alloc] init];
若我这样做,我的数组仍然有5个对象,但并没有加载到表中
array = [array init];
谢谢你的帮助
所有代码
NSArray *array;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString *request = [NSString stringWithFormat:
@"http://192.168.99.99/IBookService.svc/GetBooksNames"];
NSURL *URL = [NSURL URLWithString:
[request stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:URL options:NSDataReadingUncached error:&error];
if(!error)
{
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
array = [[NSMutableArray alloc] init];
}
_tblCustomers.dataSource = self;
_tblCustomers.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identity = @"custTbl";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identity];
if (cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:identity];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row];
return cell;
}
将对象添加到数组中,然后分配(清除)。换一种方式:
if(!error)
{
array = [[NSMutableArray alloc] init];
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
当您离开viewDidLoad方法时,当前数组被解除分配。您应该使数组成为类的成员以避免这种情况。例如,您可以添加以下内容
{
NSArray *array;
}
下线
@implementation Your_class_name_here
并删除当前行
NSArray *array;
在.h文件中添加数组,如
@property(非原子,强)NSMutableArray*数组代码>谢谢我想我已经这么做了,但不清楚@implementation ViewController NSArray*array;-(无效)viewDidLoad