I am new to ios development as well as core data, but i still tried to understand and manage with basics of these two things. Right now i am in a problem, I know how to fetch data using NSFetchedResultsController
and display them in UITableView
, but suppose if i have 20 rows
in data base and if i need to display four rows each in a section
how can i do this?. I am not getting what condition is should give for sectionNameKeyPath
while building NSFetchedResultsController
. Can somebody help me how to do this?.

- 15
- 3
1 Answers
Setting a sectionNameKeyPath
will split your NSManagedObjects
(i.e. your 'rows') based on each object's value for that key path. Let's say your objects are locations with the attributes city
and state
, e.g.
@interface Location : NSManagedObject
@property (nonatomic, retain) NSString *city;
@property (nonatomic, retain) NSString *state;
@end
If you set sectionNameKeyPath
to state
, your table view will be split into up to 50 sections. All cities with a state of @"California"
will be grouped into the @"California"
section, and so on.
If you want your 20 objects to be split into four groups, then your objects will need to have a property where 5 objects have one value for that property, 5 objects have a second value, another 5 objects have a third value, and the last 5 objects have a fourth value. You could for example create a sectionName
property:
@interface MyManagedObject : NSManagedObject
@property (nonatomic, retain) NSString *sectionName; // A, B, C, and D
@end
and set the sectionName
of 5 objects to @"A"
, another 5 to @"B"
, and so on...

- 1,520
- 13
- 21
-
Thanks for answering. But can you help me how to do this, I have date column and need create sections for each week in month. so in my table view i should see each section containing week wise entry. I am asking this help as i am beginner, if not code atleast give me idea how can i do it..?? – user3131304 Jan 10 '14 at 12:21
-
One way would be to create a `NSString` property named `formattedWeek` for your `NSManagedObject` subclass. When you set the date for an object, you could calculate which week that date is in, and then set the value of the formattedWeek (e.g. if the date is 1/10/14, you would set `formattedWeek` to `@"1/5/14 - 1/11/14"`. You could check out `NSCalendar` to help with the calculation. For more sophisticated solutions check out these other answers: [1](http://stackoverflow.com/a/4420697/2880276) [2](http://stackoverflow.com/a/1235194/2880276) [3](http://stackoverflow.com/a/7870345/2880276) – Joseph Chen Jan 10 '14 at 12:49