从数组中删除项目(使用API​​中的JSON的Restkit项目)

时间:2014-06-05 23:58:37

标签: ios arrays json restkit

我有一个leafs数组,我想删除数组中的一些对象。

数组中有 50个对象,我只想在数组中有大约10个;数组中想要的10个对象在数组中的50个对象中混合。

我在我的项目中使用RestKit,并将leafs放入表视图中。

ViewController.m

@property (strong, nonatomic) NSArray *springs;
@property (strong, nonatomic) NSMutableArray *leafs;

@end

@synthesize tableView=_tableView;
@synthesize springs;
@synthesize leafs;

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configureRestKit];
    [self loadLeafs];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)configureRestKit {
    // initialize AFNetworking HTTPClient
    NSURL *baseURL = [NSURL URLWithString:@"https://api.e.com"];
    AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];

    // initialize RestKit
    RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];

    // setup object mappings
    RKObjectMapping *springMapping = [RKObjectMapping mappingForClass:[Spring class]];
    [springMapping addAttributeMappingsFromArray:@[@"name"]];

    RKObjectMapping *leafMapping = [RKObjectMapping mappingForClass:[Leaf class]];
    [leafMapping addAttributeMappingsFromArray:@[@"abbreviation", @"shortName", @"id"]];

    [springMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"leafs" toKeyPath:@"leafs" withMapping:leafMapping]];

// Wain, this is where I'm getting that error:
// "property discardsinvalidobjectsoninsert not found on object of type RKObjectMapping"
springMapping.discardsInvalidObjectsOnInsert = YES;

    // register mappings with the provider using a response descriptor
    RKResponseDescriptor *responseDescriptor =
    [RKResponseDescriptor responseDescriptorWithMapping:springMapping
                                                 method:RKRequestMethodGET
                                            pathPattern:nil
                                                keyPath:@"springs"
                                            statusCodes:[NSIndexSet indexSetWithIndex:200]];
    [objectManager addResponseDescriptor:responseDescriptor];
}

- (void)loadLeafs {
    NSString *apikey = @kCLIENTKEY;

    NSDictionary *queryParams = @{@"apikey" : apikey,};

    [[RKObjectManager sharedManager] getObjectsAtPath:@"v1/springs/"
                                           parameters:queryParams
                                              success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                                  springs = mappingResult.array;
                                                  [self.tableView reloadData];


                                              }
                                              failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                                  NSLog(@"No springs?': %@", error);
                                              }];
}

#pragma mark - Table View

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return springs.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    Spring *spring = [springs objectAtIndex:section];
    return spring.leafs.count;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    Spring *spring = [springs objectAtIndex:section];
    return spring.name;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"standardCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    Spring *spring = [spring objectAtIndex:indexPath.section];
    Leaf *leaf = [spring.leafs objectAtIndex:indexPath.row];
    cell.textLabel.text = leaf.shortName;

    return cell;
}

Spring.h

@property (nonatomic) NSString *name;
@property (nonatomic) NSNumber *id;
@property (nonatomic) NSArray *leafs;

Leaf.h

@property (nonatomic) NSString *name;
@property (nonatomic) NSString *abbreviation;
@property (nonatomic) NSString *shortName;
@property (nonatomic) NSNumber *id;

Per Wain,我在Spring.h中添加了这个

@property (nonatomic, assign) BOOL discardsInvalidObjectsOnInsert;

Per Wain,我在Spring.m中添加了这类东西

- (BOOL)validateName:(id *)ioValue error:(NSError **)outError {

    if([(NSString *)*ioValue  isEqualToString:@"cricket"]){

        NSLog(@"old name: %@, new name: %@", self.name, *ioValue);

// Wain: set the names to nil for the objects you don't want
ioValue = nil;

        return NO;

// Wain: should I keep this line?
        self.discardsInvalidObjectsOnInsert = YES;

        }

        else{
            return YES;
        }

}

Per Wain,我在我的ViewController.m

中添加了这个
- (void)loadLeafs {

    NSString *apikey = @kCLIENTKEY;

    NSDictionary *queryParams = @{@"apikey" : apikey,};

        [[RKObjectManager sharedManager] getObjectsAtPath:@"v1/springs/"
                                               parameters:queryParams
                                                  success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                                      springs = mappingResult.array;
                                                      [self.tableView reloadData];


                                                  }
                                                  failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                                      NSLog(@"No springs?': %@", error);
                                                  }];
        // Wain: filter (using a predicate) the mapping array (name != nil)
        NSPredicate *bPredicate = [NSPredicate predicateWithValue:NO];
        self.filteredArray = [self.sports filteredArrayUsingPredicate:bPredicate];
    }

成功阻止

NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:@"name != nil"];
                                                  springs = [mappingResult.array filteredArrayUsingPredicate:filterPredicate];

                                                  // You need to loop over the springs after you filter them and then filter the leafs of each spring
                                                  for (Spring *spring in springs) {
                                                      for (Leaf *leaf in spring.leafs){
                                                          NSPredicate *filterPredicate2 = [NSPredicate predicateWithFormat:@"shortName != nil"];
                                                          leafs = [spring.leafs filteredArrayUsingPredicate:filterPredicate2];
                                                      }
                                                  }

                                                  [self.tableView reloadData];

2 个答案:

答案 0 :(得分:2)

如果要在映射期间过滤掉项目,请查看使用RestKit进行KVC验证。

如果您希望设备上的所有项目都可用且仅过滤显示,请使用谓词来过滤数组。

答案 1 :(得分:1)

按照以下方式执行操作的简单方法如下:

for (Leaf *leaf in leafs) {
    if (![leaf.shortName isEqualToString:@"aaa"] && ![leaf.shortName isEqualToString:@"bbb"] && ![leaf.shortName isEqualToString:@"ccc"] && ![leaf.shortName isEqualToString:@"ddd"]) {
        [leafs removeObject:leaf];
    }
}

它基本上遍历你的叶子对象数组,如果它遇到一个叶子对象,其shortName属性不是那四个字符串,那么该对象将被删除。