I'm a beginner with RestKit (I have some iOS experience) and I'm having some problems with my NSArray not being populated with RKMappingResult. It only populates itself in the actual 'block' but if I call to access it in viewDidLoad(), it just prints out null.
Could anyone please advise or provide any tips/links to articles?
Thanks a lot!
Here is my code -
-(void) loadData
{
RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[Venue class]];
[mapping addAttributeMappingsFromDictionary:@{
@"name": @"name", @"location.address" : @"address", @"location.city" : @"city"}];
NSString *urlString = [NSString stringWithFormat:@"https://api.foursquare.com/v2/venues/search?ll=55.903324,-3.171383&categoryId=4bf58dd8d48988d18f941735&client_id=%s&client_secret=%s&v=20130717", kCLIENTID, kCLIENTSECRET];
NSURL *baseUrl = [NSURL URLWithString:urlString];
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping method:RKRequestMethodAny pathPattern:nil keyPath:@"response.venues" statusCodes:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:baseUrl];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
//set the array of venues to be the result of what we got back
//NSLog(@"%@", [result array]);
NSArray *venues = [result array];
self.arrayOfVenues = venues; //self.arrayOfVenues is always null when I call it in the other methods
} failure:nil];
[operation start];
}
- (void) viewDidAppear:(BOOL)animated
{
[super viewDidAppear:YES];
NSLog(@"%@", self.arrayOfVenues);
}
- (void)viewDidLoad
{
[super viewDidLoad];
//load the venue data
self.title = @"Venues";
[self loadData];
NSLog(@"%@", self.arrayOfVenues);
}
Try self.arrayOfVenues = [venues copy];
I think you might be losing the reference to 'venues' when you leave the block and that variable goes away.
Also:
It only populates itself in the actual 'block' but if I call to access it in viewDidLoad(), it just prints out null.
Bear in mind, this block needs to complete BEFORE you try to access the array. viewDidLoad is definitely going to fire before this block finishes, and so will viewDidAppear.