Subarray with range

后端 未结 3 811
南笙
南笙 2021-01-26 11:31

Im trying to split an array of objects into smaller arrays containing 32 objects. With the remaining about being put into the array at the end.

This is the code I\'m usi

相关标签:
3条回答
  • 2021-01-26 11:52

    2nd parameter of NSMakeRange is length range to create, not the last index in it. So you need to change your code accordingly (simplifying it a bit):

    NSUInteger count = sharedManager.inventoryArray2.count;
    NSMutableArray *arrayOfArrays = [NSMutableArray array];
    NSUInteger from = 0;
    while (from < count) {
        NSRange range = NSMakeRange(from, MIN(32, count-from));
        NSArray *smallArray = [sharedManager.inventoryArray2 subarrayWithRange:range];
        [arrayOfArrays addObject:smallArray];
    
        from += 32;
    }
    
    0 讨论(0)
  • 2021-01-26 11:52

    No Actually the range doesn't work like this NSRange {32, 63} => means from the index 32 take 63 elements

    Here is documentation :

    NSRange
    
    A structure used to describe a portion of a series—such as characters in a string or objects in an NSArray object.
    
    typedef struct _NSRange {
      NSUInteger location;
      NSUInteger length;
     } NSRange;
    
     location
    The start index (0 is the first, as in C arrays). For type compatibility with the rest of the system, LONG_MAX is the maximum value you should use for location.
    
     length
    The number of items in the range (can be 0). For type compatibility with the rest of the system, LONG_MAX is the maximum value you should use for length.
    
    0 讨论(0)
  • 2021-01-26 11:53

    A NSRange indicates the starting point and the number of entries to select from that point on.. So it actually means "Starting point 32, select 63 items from that point on", which will exceed your 83 entries (32*+*63)

    0 讨论(0)
提交回复
热议问题