如何从一个数组创建多个数组?

时间:2015-10-02 13:58:48

标签: ios objective-c iphone arrays logic

我有一个数组“values1”总共有104个项目,我需要创建1个13个子数组的数组,每个子数组应该有8个值。

例如,如果“values1”具有item:

1,2,3,4,5 ..., 13,
14,15,15,... , 26,
27,28,29,...

我需要像这样的子数组:

first subarray: 1,14,27, ....
second subarray: 2,15,18,...

这就是我需要在一个单独的数组中创建13个subArrays的方法。

NSString *strFileContent = [NSString stringWithContentsOfFile:[[NSBundle mainBundle]
                                                               pathForResource: @"values" ofType: @"txt"] encoding:NSUTF8StringEncoding error:nil];
NSArray *values1 = [strFileContent componentsSeparatedByString:@"@@"];

2 个答案:

答案 0 :(得分:0)

NSString *strFileContent = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource: @"values" ofType: @"txt"] encoding:NSUTF8StringEncoding error:nil];
NSArray *values1 = [strFileContent componentsSeparatedByString:@"@@"];
NSMutableArray *graph1Values = [[NSMutableArray alloc]init];

for (int a=0; a<13; a++) {
NSMutableArray *newarray1 = [[NSMutableArray alloc] init];
for(int i=a; i<values1.count; i=i+13){
    [newarray1 addObject:[values1 objectAtIndex:i]];
}
    [graph1Values addObject:newarray1];
}

NSLog(@"%@",graph1Values);

答案 1 :(得分:0)

这是一个很小的类别:

的NSArray + Split.h

#import <Foundation/Foundation.h>

@interface NSArray (Split)

-(NSArray *) splitIntoSubarrays:(NSInteger) count;

@end

的NSArray + Split.m

#import "NSArray+Split.h"

@implementation NSArray (Split)

-(NSArray *) splitIntoSubarrays:(NSInteger) count 
{
    NSMutableArray *arrayOfArrays = [[NSMutableArray alloc] init];

    for (NSInteger i = 0; i < self.count; i++)
    {
        if (i < count)
        {
            arrayOfArrays[i] = [[NSMutableArray alloc] init];
        }
        [arrayOfArrays[i % count] addObject:self[i]];
    }
    return arrayOfArrays;
}

@end

用法:

#import "NSArray+Split.h"

(...)

    NSArray *arrayOfArrays = [initialArray splitIntoSubarrays:13];