在添加新对象时,通过继承属性对自定义对象的NSArray进行排序

时间:2014-05-04 22:50:23

标签: ios objective-c sorting

类“Person”由“EmployeeList”继承的“Employee”继承

在我的主模型中,我初始化一个新的Employee对象,将firstNamelastName,然后addEmployee设置为EmployeeList

addEmployee方法中,我希望按lastName

对员工对象的NSArray进行排序

这是我尝试过的,但它没有对列表进行排序。

#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];

2 个答案:

答案 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++;
}

要小心,因为你自己的员工是可变的。