类“Person”由“EmployeeList”继承的“Employee”继承
在我的主模型中,我初始化一个新的Employee
对象,将firstName
和lastName
,然后addEmployee
设置为EmployeeList
。
在addEmployee
方法中,我希望按lastName
这是我尝试过的,但它没有对列表进行排序。
#import "EmployeeList.h"
@interface EmployeeList()
@property (strong, nonatomic) NSMutableArray *employees; // of Employee
@end
@implementation EmployeeList
- (NSMutableArray *)employees
{
if (!_employees) _employees = [[NSMutableArray alloc] init];
return _employees;
}
- (void)addEmployee:(Employee *)employee
{
[self.employees addObject:employee];
NSSortDescriptor *sortDescriptor =
[NSSortDescriptor sortDescriptorWithKey:@"lastName"
ascending:YES
selector:@selector(caseInsensitiveCompare:)];
[self.employees sortedArrayUsingDescriptors:@[sortDescriptor]];
_numberEmployees++;
}
主要型号:
EmployeeList *mgrList = [[EmployeeList alloc] init];
Employee *employee = [[Employee alloc] init];
employee.firstName = object[@"firstName"];
employee.lastName = object[@"lastName"];
employee.phoneNumber = object[@"phoneNumber"];
[mgrList addEmployee:employee];
答案 0 :(得分:2)
改变这个:
[self.employees sortedArrayUsingDescriptors:@[sortDescriptor]];
为:
[self.employees sortUsingDescriptors:@[sortDescriptor]];
答案 1 :(得分:1)
好的,你的代码需要一个重构:
#import "EmployeeList.h"
@interface EmployeeList()
@property (strong, nonatomic) NSMutableArray *employees; // of Employee
@end
@implementation EmployeeList
//This is a more elegant solution to init
- (NSMutableArray *)employees
{
dispatch_token_t token;
dispatch_once(&token, ^{
_employees = [NSMutableArray new];
});
return _employees;
}
- (void)addEmployee:(Employee *)employee
{
[self.employees addObject:employee];
NSSortDescriptor *sortDescriptor =
[NSSortDescriptor sortDescriptorWithKey:@"lastName"
ascending:YES
selector:@selector(caseInsensitiveCompare:)];
//This return an array so if you don't take it you don't have any change.
NSArray *newArray = [[self.employees copy] sortedArrayUsingDescriptors:@[sortDescriptor]];
//Then you can remove and add again all the object to the NSMutableArray
[self.employees removeAllObjects];
[self.employees addObjectsFromArray:newArray];
//This is not needed because you can access to this information by
//[self.employees count]
//_numberEmployees++;
}
要小心,因为你自己的员工是可变的。