0

I'm having difficulty figuring out how to incorporate a counter so the "setObject" increments it's 'Save' in this for..loop.

   NSMutableArray *NewArray = [NSMutableArray new];
   NSMutableDictionary *dict = [NSMutableDictionary dictionary];


     for ( DBFILESMetadata *entry in result.entries) {

        [dict setObject:entry.pathDisplay forKey:@"pathDisplay"];

        [dict setObject:entry.name forKey:@"name"];

        [NewArray addObject:dict];

     }

I'm sure this is an easy answer,the last line is only saving the last item of result.entries. The NewArray has the correct count of items, but every item in the array is the last item of result.entries:

2017-04-13 16:47:58.876 Sites[11145:688352] NewArray (
     {
     name = 229;
     pathDisplay = "/Sites/229";
     },
     {
     name = 229;
     pathDisplay = "/Sites/229";
    }
  ).

I need to add a counter of some type to set the next object, just confused on where it should go.

Thanks in advance.

I figured this out:

  for ( DBFILESMetadata *entry in result.entries) {

        [imagePaths addObject:entry.pathDisplay];
        [names addObject:entry.name];
     }

     for(int i=0; i<[result.entries count]; i++) {
         dict = @{@"name": names[i], @"pathDisplay": imagePaths[i]};
         [allObjects addObject:dict];
     }
Michael Robinson
  • 1,439
  • 2
  • 16
  • 23

1 Answers1

0

The dictionary item keys must be different. Otherwise, you see always last set item. Because the dictionary will overide when the save same key. So you can use just like below.

1.Solutions

NSMutableArray *NewArray = [NSMutableArray new];

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

 int i = 0;
 for ( DBFILESMetadata *entry in result.entries) {
   
    [dict setObject:entry.pathDisplay forKey:[NSString stringWithFormat:@"pathDisplay%d",i]];

    [dict setObject:entry.name forKey:[NSString stringWithFormat:@"name%d",i]];

    [NewArray addObject:dict];
     i++;

 }

2.Solution

Create a class that will hold the json property, just like a below.

HoldJsonDataClass.h
    @interface HoldJsonDataClass : JsonData
    @property (nonatomic,retain) NSString *name;
    @property (nonatomic,retain) NSString * pathDisplay;
    @end

HoldJsonDataClass.m    
    @implementation HoldJsonDataClass
    
    @end

And than fill the class to the array. This solution is more clear.

    for ( DBFILESMetadata *entry in result.entries) {

    HoldJsonDataClass *holdJsonClass = [HoldJsonDataClass new];
    holdJsonClass.name = entry.name;
    holdJsonClass.pathDisplay = entry.pathDisplay;
    [NewArray addObject:holdJsonClass];
 }
Community
  • 1
  • 1
Emre Gürses
  • 1,992
  • 1
  • 23
  • 28