NSDate
プロパティを含むオブジェクトの配列があります。そして、私はそれらをUITableView
.
UITableView
それら(オブジェクト)を月ごとにセクションに分けて配布したいと思います。
どうやってやるの?
NSDate
プロパティを含むオブジェクトの配列があります。そして、私はそれらをUITableView
.
UITableView
それら(オブジェクト)を月ごとにセクションに分けて配布したいと思います。
どうやってやるの?
以下のコードを使用して、オブジェクト (Person など) をグループ化できます。
NSMutableArray* arrObjects = [NSMutableArray new];
for (int i=0;i<12;i++) {
Person* p1 = [Person new];
p1.name = [NSString stringWithFormat:@"ABC %d", i+1];
p1.date = [[NSDate date] dateByAddingTimeInterval:60*60*24*30*i];
[arrObjects addObject:p1];
}
// add blank arrays for 12 months
NSMutableArray* matrixObjects = [NSMutableArray new];
for (int i=0; i<12; i++) {
[matrixObjects addObject:[NSMutableArray new]];
}
NSCalendar* calendar = [NSCalendar currentCalendar];
for (Person* p in arrObjects) {
int month = (int) [[calendar components:NSCalendarUnitMonth fromDate:p.date] month];
[matrixObjects[month-1] addObject:p];
}
// print resutls
for (int i=0; i<matrixObjects.count; i++) {
NSLog(@"Objects in Section %d", i);
for (Person* p in matrixObjects[i]) {
NSLog(@" ROW: %@ %@", p.name, p.date.description);
}
}
次のような出力が得られます。
Objects in Section 0
ROW: ABC 11 2017-01-29 11:55:49 +0000
Objects in Section 1
ROW: ABC 12 2017-02-28 11:55:49 +0000
Objects in Section 2
Objects in Section 3
ROW: ABC 1 2016-04-04 11:55:49 +0000
Objects in Section 4
ROW: ABC 2 2016-05-04 11:55:49 +0000
Objects in Section 5
ROW: ABC 3 2016-06-03 11:55:49 +0000
Objects in Section 6
ROW: ABC 4 2016-07-03 11:55:49 +0000
Objects in Section 7
ROW: ABC 5 2016-08-02 11:55:49 +0000
Objects in Section 8
ROW: ABC 6 2016-09-01 11:55:49 +0000
Objects in Section 9
ROW: ABC 7 2016-10-01 11:55:49 +0000
ROW: ABC 8 2016-10-31 11:55:49 +0000
Objects in Section 10
ROW: ABC 9 2016-11-30 11:55:49 +0000
Objects in Section 11
ROW: ABC 10 2016-12-30 11:55:49 +0000
matrixObjectsは、 numberOfSectionsおよびnumberOfRowsデリゲート メソッドで使用できるオブジェクトの 12 か月ごとの配列の配列です。