Search code examples
iosobjective-carraysnsarrayobjective-c-blocks

Data inside array not visible outside of block in iOS


I am working on an iOS application where I parse data from a csv file. I am able to parse the data successfully, store the data into an array, and then print the contents of the array to the console. However, I am unable to view the contents of the array outside of the block where I do the iteration. Here is the code that I am working with:

#import "TestData.h"

@interface TestData ()

@property (nonatomic, strong) NSMutableArray *array;

@end

@implementation TestData

- (void) addData {


    NSString *file = [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"csv"];

    [self.array = [[NSMutableArray alloc] init];
     __weak TestData *wSelf = self;
    [CSVParser parseCSVIntoArrayOfArraysFromFile:file
                withSeparatedCharacterString:@","
                        quoteCharacterString:nil
                                   withBlock:^(NSArray *array, NSError *error) {
                                       __strong TestData *sSelf  = wSelf;
                                       [sSelf.array setArray: array];
                                       //self.array = array;
                                       //NSLog(@"%@", self.array);

                                   }];
     NSLog(@"%@", self.array);

}

I would like to use the full contents of self.array outside of the block. Can anyone see what it is I am doing wrong?


Solution

  • Try this:

    self.array = [[NSMutableArray alloc] init];
    __weak MyViewController *wSelf = self;
    [CSVParser parseCSVIntoArrayOfArraysFromFile:file
                withSeparatedCharacterString:@","
                        quoteCharacterString:nil
                                   withBlock:^(NSArray *array, NSError *error) {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                            __strong MyViewController *sSelf  = wSelf;
                                           [sSelf doSomethingWithMyData:array];
                                       }
                                   }];
    

    Also, if your parser is asynchronous, your log statement outside of the block may be printing before the parsing of your data has actually completed.

    Also, by using the weak and strong references to self inside your block, you avoid retain cycles.