i’m following a tutorial on iPhone on how to display data from a remote database onto the iPhone. The tutorial is fine however i dont understand one part (and also have some other queries) and was hoping someone mind shed some light.
Corresponding to the code below, what does “rows = [[dict objectForKey:@”users”] retain];” do? (its looking for the key – “users” and storing all results into rows? – but what is row? is it referring to the table row?). And if so, how can this data be sorted depending on the database information and not the fields?
My second question is, how can i manipulate the data so, only fields with certain string values show in the table?
Thanks for any help with this!
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://localhost:8888/jsontest.php"]; // Modify this to match your url.
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url]; // Pulls the URL
NSLog(jsonreturn); // Look at the console and you can see what the restults are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
rows = [[dict objectForKey:@"users"] retain];
}
NSLog(@"Array: %@",rows);
[jsonreturn release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [rows count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
NSDictionary *dict = [rows objectAtIndex: indexPath.row];
cell.textLabel.text = [dict objectForKey:@"userid"];
cell.detailTextLabel.text = [dict objectForKey:@"email"];
return cell;
}
Judging from this block here:
it would appear that
rows = [[dict objectForKey:@"users"] retain];is referring to an array. Looking at the remaining code, it looks to be an array ofNSDictionaryobjects containing user information.The best approach to show only a certain subset of the result set would be to create a second array that contains the objects that match your criteria and use that as your tableview datasource.