Creating a New Array in each iteration of For Loop - ios

After so long, I'm still trying to create my first iOS app, and I'm facing another problem yet again =(
Basically, I have pulled JSON data from the web, and I get nested arrays. I have no problems iterating all objects in the array (including the parent array) and placing them in a UITableView. The problem is, I am trying to do something dynamic for the table. I am able to create the correct number of sections for the table. To make it easy for you to visualise what I want to do, here is the JSON data:
{"filter_group":[{"filter_group_id":"1","name":"Location","filter":[{"filter_id":"2","name":"Central"},{"filter_id":"8","name":"East"},{"filter_id":"1","name":"North"},{"filter_id":"10","name":"Northeast"},{"filter_id":"9","name":"West"}]},{"filter_group_id":"3","name":"Price","filter":[{"filter_id":"7","name":"Free"},{"filter_id":"5","name":"$0 - $50"},{"filter_id":"6","name":"$50 - $100"},{"filter_id":"11","name":"$100 - $150"},{"filter_id":"12","name":"$150 - $200"},{"filter_id":"13","name":"Above $200"}]}]}
When you copy the messy chunk that I give you into any JSON viewer, you will see that for now, I have 2 parent arrays with some children each. So basically, "Location" and "Price" will go into different sections. I have successfully done that, but I don't know how to put the names of their children in the correct section of the UITableView.
So my idea now is that I am iterating the array, and putting the children names into another array (this results in names of both sections going into 1 array). I was thinking of creating a new array in each iteration:
for(int i = 0; i < [myArray count]; i++) {
//throw children of different parents into different array
NSMutableArray* newArray[i] = (blah blah blah)
}
You will probably have seen the problem now: newArray[i]. Basically, I can live with the fact that I am creating newArray0, newArray1 etc (I need my app to be dynamic). How do I do this in iOS programming?
OR
After reading what I want to do above, and you have a different idea on how I am to put the data in the respective sections, please enlighten me.
Thank you very much!!! I greatly appreciate any help offered =D
P.S. My replies may be slow, so please forgive me

In your application you can use array from json object. I've made sample project to illustrate this aproche:
In header file (ViewController.h):
#import <UIKit/UIKit.h>
#interface ViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource>
#property (nonatomic, strong) NSMutableArray *data;
#property (nonatomic, strong) NSMutableArray *sectionTitles;
#end
and in ViewController.m file:
#import "ViewController.h"
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *jsonString = #"{\"filter_group\":[{\"filter_group_id\":\"1\",\"name\":\"Location\",\"filter\":[{\"filter_id\":\"2\",\"name\":\"Central\"},{\"filter_id\":\"8\",\"name\":\"East\"},{\"filter_id\":\"1\",\"name\":\"North\"},{\"filter_id\":\"10\",\"name\":\"Northeast\"},{\"filter_id\":\"9\",\"name\":\"West\"}]},{\"filter_group_id\":\"3\",\"name\":\"Price\",\"filter\":[{\"filter_id\":\"7\",\"name\":\"Free\"},{\"filter_id\":\"5\",\"name\":\"$0 - $50\"},{\"filter_id\":\"6\",\"name\":\"$50 - $100\"},{\"filter_id\":\"11\",\"name\":\"$100 - $150\"},{\"filter_id\":\"12\",\"name\":\"$150 - $200\"},{\"filter_id\":\"13\",\"name\":\"Above $200\"}]}]}" ;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
NSArray *filter_groups = [result objectForKey:#"filter_group"];
self.data = [[NSMutableArray alloc] initWithCapacity:[filter_groups count]];
self.sectionTitles = [[NSMutableArray alloc] initWithCapacity:[filter_groups count]];
for (NSDictionary *filter_group in filter_groups) {
NSArray *filters = [filter_group objectForKey:#"filter"];
[self.data addObject:filters];
[self.sectionTitles addObject:[filter_group objectForKey:#"name"]];
}
NSLog(#"%#", self.data);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
return self.sectionTitles[section];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return [self.data count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
NSArray *sectionArray = self.data[section];
return [sectionArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"testCell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"testCell"];
}
NSArray *sectionArray = self.data[indexPath.section];
NSDictionary *filter = sectionArray[indexPath.row];
cell.textLabel.text = [filter objectForKey:#"name"];
return cell;
}
#end
If you have same question to code, feel free to ask. You can grab code from https://gist.github.com/MaciejGad/8452791

create a new temp array in each loop and add that new temp array to a Mutable array, it is similar to new array[i], while retrieving NSArray *array = [mutablearray objectAtIndex:i]`

please try the following code.
NSMutableDictionary *responseDict; // assign value to responseDict from your response
NSMutableArray *mainArray=[[NSMutableArray alloc] initWithArray:[responseDict objectForKey:#"filter_group"]];
for(int i=0;i<[mainArray count];i++)
{
if([[[mainArray objectAtIndex:i] objectForKey:#"name"] isEqualToString:#"Price"])
{
NSArray *pricechildArray=[[mainArray objectAtIndex:i] objectForKey:#"filter"];
}
else if([[[mainArray objectAtIndex:i] objectForKey:#"name"] isEqualToString:#"Location"])
{
NSArray *locationchildArray=[[mainArray objectAtIndex:i] objectForKey:#"filter"];
}
}
hope this will help you.

Related

Multi level categories with items on all levels in UITableView

I have to create a UITableView using the JSON response below ( Array ). I have no code for this yet but would love some direction to how i would split this array to accommodate categories and items on all levels.
{
"result":{
"products":[
{
"id":"4",
"product_code":"PR04",
"title":"Product1",
"franchisee_id":"118"
}
],
"categories":[
{
"id":"8",
"name":"Category1"
},
{
"id":"20",
"name":"Category2",
"products":[
{
"id":"9",
"product_code":"PR07",
"title":Product2,
"franchisee_id":"118"
}
]
}
]
}
}
I want to achieve the following result:
items
Category1 > items
Category2 > items
When a category is clicked it would slide to the products in that category. Would really love some direction on this. Some products will not be in categories. Like the example above.
Well....
You need to parse the JSON file. You can easily google for some tutorials but here is a decent one.
Next you are going to need to setup a UITableView to load the items. another good tutorial on UITableViews
Then you are going to need to learn how to pass data between UIViewControllers. Tutorial.
So your steps in the code will be to:
Parse the JSON to separate all the elements.
Setup a UITableView to display the top level elements.
Create a second UITableViewController to push to after a top level item has been selected.
Setup a custom initializer for the second UITableViewController so you can pass it relevant data from the first view controller where you parsed the JSON.
I'm assuming you were looking for a bunch of code on how to do this, but that's no fun :)
Let me know if you run into any troubles and I will be glad to help.
EDIT:
I know I said I wasn't going to dump code but I have some extra time.
Create an NSObject subclass called ProductObject and make the .h look like this:
#import <Foundation/Foundation.h>
#interface ProductObject : NSObject
#property NSString *productCode, *productTitle, *franchiseId, *productId;
#end
Don't do any thing to the .m
Create another NSObject subclass called CategoryObject and make the .h look like this:
#import <Foundation/Foundation.h>
#interface CategoryObject : NSObject
#property NSString *categoryName, *categoryId;
#property NSArray *products;
#end
Again, don't need to do anything to the .m.
Now, in the class that you want to display the UITableView will the Products and Categories (this is all in the .m, the .h is empty):
#import "ViewController.h"
#import "CategoryObject.h"
#import "ProductObject.h"
#interface ViewController ()
//Hooked in from IB
#property (weak, nonatomic) IBOutlet UITableView *table;
//Our UITableView data source
#property NSMutableDictionary *tableObjects;
#end
#implementation ViewController
/**
Parses a the local JSON file
*/
- (void)parseJSON {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"json"];
//création d'un string avec le contenu du JSON
NSString *myJSON = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSError *error;
NSDictionary *topLevleJSON = [NSJSONSerialization JSONObjectWithData:[myJSON dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
if (error) {
NSLog(#"Error serializing JSON: %#", error.localizedDescription);
return;
}
NSArray *products = topLevleJSON[#"products"];
NSArray *categories = topLevleJSON[#"categories"];
//Use a NSDictonary so that it contains an NSArray of ProductObjects for the "Products" key, and an array of CategoryObjects for the "Category" key.
self.tableObjects = [NSMutableDictionary new];
//Parse all the products
NSMutableArray *productsInJSON = [NSMutableArray new];
[products enumerateObjectsUsingBlock:^(NSDictionary *productObject, NSUInteger idx, BOOL *stop) {
ProductObject *product = [self createProductObjectFromDictionary:productObject];
[productsInJSON addObject:product];
}];
//Set the array of ProductObjects for the key #"Products"
[self.tableObjects setObject:productsInJSON forKey:#"Products"];
//Parse all the categories
NSMutableArray *categoriesInJSON = [NSMutableArray new];
[categories enumerateObjectsUsingBlock:^(NSDictionary *categoryObject, NSUInteger idx, BOOL *stop) {
CategoryObject *category = [self createCategoryObjectFromDictionary:categoryObject];
[categoriesInJSON addObject:category];
}];
//Set the array of CategoryObjects for key #"Categories"
[self.tableObjects setObject:categoriesInJSON forKey:#"Categories"];
[self.table reloadData];
}
/**
Creates a ProductObject from an NSDictonary.
#param dictionary The dictonary describing the Product parsed from JSON
#return A pretty formatted ProductObject
*/
- (ProductObject*)createProductObjectFromDictionary:(NSDictionary*)dictionary {
ProductObject *product = [ProductObject new];
product.productTitle = dictionary[#"title"];
product.productCode = dictionary[#"product_code"];
product.franchiseId = dictionary[#"franchisee_id"];
product.productId = dictionary[#"id"];
return product;
}
/**
Creates a Category from an NSDictionary
#param dictionary The dictonary describing the Category parsed from JSON
#return A pretty formatted CategoryObject
*/
- (CategoryObject*)createCategoryObjectFromDictionary:(NSDictionary*)dictionary {
CategoryObject *category = [CategoryObject new];
category.categoryId = dictionary[#"id"];
category.categoryName = dictionary[#"name"];
//Check to see if the "products" key exist for the category, if we don't check and just look for it, we will get a crash if it doesn't exist.
if ([[dictionary allKeys] containsObject:#"products"]) {
NSArray *categoryProducts = dictionary[#"products"];
//Parse all the Products for the Category.
NSMutableArray *categoryProductsFormatted = [NSMutableArray new];
[categoryProducts enumerateObjectsUsingBlock:^(NSDictionary *productObject, NSUInteger idx, BOOL *stop) {
ProductObject *product = [self createProductObjectFromDictionary:productObject];
[categoryProductsFormatted addObject:product];
}];
category.products = [NSArray arrayWithArray:categoryProductsFormatted];
}
else {
category.products = nil;
}
return category;
}
#pragma mark -
#pragma mark - UITableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.tableObjects allKeys] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//Get the key for this section
NSString *key = [[self.tableObjects allKeys] objectAtIndex:section];
//Return the number of objects for this key.
return [(NSArray*)[self.tableObjects objectForKey:key] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [[self.tableObjects allKeys] objectAtIndex:section];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"CellIdentifier"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"CellIdentifier"];
}
//Get all the NSArray associated with this section, which will be an array of ProductObjects or an array of CategoryObjects
NSString *key = [[self.tableObjects allKeys] objectAtIndex:indexPath.section];
NSArray *sectionobjects = (NSArray*)[self.tableObjects objectForKey:key];
id object = [sectionobjects objectAtIndex:indexPath.row];
//Set the cell text based on what kind of object is returned
if ([object isKindOfClass:[ProductObject class]]) {
cell.textLabel.text = [(ProductObject*)object productTitle];
}
else if ([object isKindOfClass:[CategoryObject class]]) {
cell.textLabel.text = [(CategoryObject*)object categoryName];
}
return cell;
}
#pragma mark -
#pragma mark - UITableView delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *key = [[self.tableObjects allKeys] objectAtIndex:indexPath.section];
NSArray *sectionobjects = (NSArray*)[self.tableObjects objectForKey:key];
id object = [sectionobjects objectAtIndex:indexPath.row];
//They selected a product
if ([object isKindOfClass:[ProductObject class]]) {
ProductObject *product = (ProductObject*)object;
NSLog(#"%#", product.productTitle);
NSLog(#"%#", product.productCode);
NSLog(#"%#", product.productId);
}
//They selected a Category
else if ([object isKindOfClass:[CategoryObject class]]) {
//Check to see if the CategoryObject has any ProductObjects associated with it
if ([(CategoryObject*)object products]) {
//Now you will need to pass array of ProductObjects this along to your next view controller.
NSArray *cateogryProducts = [(CategoryObject*)object products];
//For demonstration purposes, i'll run through and print out all the Products for this Category
[cateogryProducts enumerateObjectsUsingBlock:^(ProductObject *product, NSUInteger idx, BOOL *stop) {
NSLog(#"%#", product.productTitle);
NSLog(#"%#", product.productCode);
NSLog(#"%#", product.productId);
}];
}
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//Start parsing the JSON
[self parseJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
EDIT:
If you are wanting to open and close parts of the table like an accordion, take a look at Apple's same code: Table View Animations and Gestures.

Cannot Feed UITableView with .plist

I am a beginner and have a probably quite simple question. I browsed through similar topics and lost a day without finding a solution.
I have a Master and Detail view controllers. I created a .plist as shown below.
Now I would like feed UITableView with these data. And here the problem is. I can't take continents names. All the time I see blank cells or I get some errors. Maybe I should change something in the plist?
Here is my code:
MasterViewController.h:
#interface MasterViewController : UITableViewController
#property (nonatomic, strong) NSDictionary *world;
#property (nonatomic, strong) NSDictionary *africa;
#property (nonatomic, strong) NSDictionary *europe;
#end
MasterViewController.m (the places where I added something):
#synthesize world, africa, europe;
- (void)viewDidLoad
{
self.navigationItem.title = #"World Info";
NSString *worldLibraryFile = [[NSBundle mainBundle] pathForResource:#"World" ofType:#"plist"];
world = [[NSDictionary alloc] initWithContentsOfFile:worldLibraryFile];
africa = [world objectForKey:#"Africa"];
europe = [world objectForKey:#"Europe"];
[super viewDidLoad];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [world count]; //this works fine
}
And here I have a problem:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *ContinentName = [world objectForKey:indexPath.row]; //I do something wrong here
cell.textLabel.text = ContinentName;
return cell;
}
How can I get my continents shown in the table view? How to get countries and then other info shown after another clicks?
Thank you for any help.
It works now, after these changes:
NSArray *namesOfContintents = [world allKeys];
NSString *ContinentName = [namesOfContintents objectAtIndex:indexPath.row];
cell.textLabel.text = ContinentName;
I also wanted to add some subtitles to the cells. I added:
int numberEurope;
numberEurope = [europe count];
int numberAfrica;
numberAfrica = [africa count];
NSNumber *myNum1 = [NSNumber numberWithInt:numberEurope];
NSNumber *myNum2 = [NSNumber numberWithInt:numberAfrica];
NSArray *myArray = [NSArray arrayWithObjects: myNum1, myNum2, nil];
cell.textLabel.text = ContinentName;
cell.detailTextLabel.text = [[NSString alloc] initWithFormat:#"%# countries", myArray];
return cell;
But the subtitles are the same in every cell: ( 2, 2) countries instead of 2 countries in the first cell and 2 countries in the second one. What am I doing wrong?
NSString *ContinentName = [world objectForKey:indexPath.row];
the objectForKey is expecting a name for the key, you´re giving in an int.
try this:
NSDictionary *ContinentName = [world objectForKey:#"Europe"];
Also, the value returning here is a NSDictionary, not a String.
I recommend converting your continents to a flat array.
NSMutableArray *flatArray = [[NSArray alloc] init];
for(id item in world){
[flatArray addObject:item];
}
This array you can access via the indexPath.row
If you want the names of the continents you can call.
NSArray *namesOfContintents = [world allKeys];

Why is my NSMutableArray data for a UITableView getting lost by the time it gets used by tableView:cellForRowAtIndexPath?

I have an NSMutableArray *rows; that I initialize and populate with data in viewDidLoad. At that point, obviously, it has data. In this case, three entries.
Then inside tableView:cellForRowAtIndexPath I'm calling [rows objectAtIndex:indexPath.row]. However, at this point the rows array still contains three entries but the values of those entries are 0x00000000 instead of the original value (e.g. 'id' was 12345 but is now 0x00000000.
It seems to me that somehow the value of the data in rows is getting emptied somewhere between viewDidLoad and tableView:cellForRowAtIndexPath. What could be causing this?
EDIT
Here is the code:
ViewController.m:
#implementation ViewController
NSMutableArray *rows;
- (void)viewDidLoad
{
rows = [[NSMutableArray alloc] init];
[rows setArray:myData]; // myData is als an NSMutableArray populated from JSON data.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
User *user = [rows objectAtIndex:indexPath.row]; // At this point 'rows' contains three entries but the values are empty.
}
#end
EDIT 2
Here is the code after several suggested changes:
ViewController.m
#interface ViewController()
{
NSMutableArray *rows;
}
#implementation ViewController
- (void)setRowsFromJSON
{
NSString *fileContents = [NSString stringWithContentsOfFile:#"data.json" encoding:NSUTF8StringEncoding error:nil];
NSData *jsonData = [fileContents dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
rows = [NSMutableArray arrayWithCapacity:[jsonArray count]];
User *user;
for (NSDictionary *aUser in jsonArray) {
user = [[User alloc] init];
user.id = [aUser valueForKey:#"id"];
user.name = [aUser valueForKey:#"name"];
[rows addObject:user];
}
}
- (void)viewDidLoad
{
[self setRowsFromJSON];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
User *user = [rows objectAtIndex:indexPath.row]; // At this point 'rows' contains three entries but the values are empty.
}
#end
0x000000000 is nil. That means that row is pointing to nowhere.
I had the same problem running an app on iOS 5.1. The problem is you are supposing that viewDidLoad is always invoked before tableview:cellForRowAtIndexPath:. But that doesn't have to be that way. The first is a method of the view controller. The second is a method of the Table View Data Source. The fact that both are the same object is an accident.
In my case, the Table View Controller methods where invoked before viewDidLoad and then, after viewDidLoad, invoked again 'cause some modifications of properties of the View Table always make a reload.
Try to initialize in, for example, – numberOfSectionsInTableView:

How to rollup similar rows in UITableView like iOS Phone Recents using Core Data

What is the best way to rollup similar rows in UITableView like the Phone's Recents tab. I'm using Core Data and currently displaying data chronologically based on a "timestamp" field in my NSManagedObject. The iPhone Recents table groups like rows into one row to compress redundant data.
What is the best way to accomplish this?
I'm sure that Apple has some easier way they do it in their code, but here is what I came up with. There is 1 NSArray (with some raw data) that I instantiate in the viewDidLoad method, and then 2 NSMutableArray's that are declared as properties (and lazily instantiated) in the .h file. Here is my code.
.h
#interface RollUpTableViewController : UITableViewController
#property (strong, nonatomic) IBOutlet UITableView *rollUpTableView;
#property (strong, nonatomic) NSMutableArray *names;
#property (strong, nonatomic) NSMutableArray *countOfNames;
#end
.m
-(NSMutableArray *)names{
if(!_names) _names = [[NSMutableArray alloc]init];
return _names;
}
-(NSMutableArray *)countOfNames{
if (!_countOfNames) _countOfNames = [[NSMutableArray alloc] init];
return _countOfNames;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *rawData = [[NSArray alloc] initWithObjects:#"Jack", #"Jill", #"Jill", #"Ryan", #"Bill", #"Ryan", #"Ryan", #"Ryan", #"Steve", #"Katie", #"Jill", #"Ryan", #"Ryan", nil];
int countOfLikeNames = 0;
int i=0;
for (i = 0; i < [rawData count]; i++){
if (i == 0) {
//Putting the first name in the names NSMutableArray no matter what
[self.names addObject:[rawData objectAtIndex:i]];
countOfLikeNames = countOfLikeNames + 1;
} else {
//Checking if the current name is the same as the previous
if ([rawData objectAtIndex:i] == [rawData objectAtIndex:(i-1)]) {
countOfLikeNames = countOfLikeNames + 1;
} else {
//Once it runs into a difference in names, add the final count to the countOfNames NSMutableArray
[self.countOfNames addObject:[NSNumber numberWithInt:countOfLikeNames]];
//Starting the count over
countOfLikeNames = 1;
//Adding the next name
[self.names addObject:[rawData objectAtIndex:i]];
}
}
//if the for loop is on its last iteration, add what will be the last object for countOfNames
if (i == ([rawData count] - 1)) {
[self.countOfNames addObject:[NSNumber numberWithInt:countOfLikeNames]];
}
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.names count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.textLabel.text = [self.names objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [[self.countOfNames objectAtIndex:indexPath.row] stringValue];
return cell;
}
#end
I was a bit lazy and just used Apple's built in 'Right Detail' style on the UITableViewCell and this is what resulted from the raw data.
You would have to compare the time stamps that you have from your CoreData, but hopefully this helps you with the concept.

Can't access the instance variable

I have an UTableView grouped. I want to split my data into "categories" group. I have an instance variable which contains all groups in my database.
#interface TableViewController : UITableViewController {
// Response from server
NSString* serverResponse;
NSMutableArray *categories; // This NSMutableArray contains all category's server
}
#property (strong) NSString *serverResponse;
#property (strong) NSMutableArray *categories;
I fill my NSMutableArray with the requestFinished method (where all works perfectly)
- (void)requestFinished:(ASIHTTPRequest *)request
{
NSString *result = request.responseString;
NSArray *jsonArray = (NSArray*)[result JSONValue];
int count = [jsonArray count];
int i;
NSDictionary *jsonDict = [[NSDictionary alloc] init];
for (i = 0; i < count; i++) {
jsonDict = [jsonArray objectAtIndex:i];
NSString *current = [jsonDict objectForKey:#"categoriy"];
[categories addObject:current];
NSLog(#"%d", [categories count]) // Shows 4 -> ok !
}
}
But when I call it in this method :
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(#"%d", [categories count]) // Show 0 -> bad !
return [categories count];
}
It shows on the consol "0" !
I really dont understand why !
Perhaps someone could help me with this?
The problem might be that numberOfSectionsInTableView: is called before the requestFinished: is called.
I think you have to reload the tableview.
Try putting [self.tableView reloadData], or something like that, at the end of requestFinished:.

Resources