Instance variable not storing value in iOS app

I declared this ivar in my

ViewController.h

#import <UIKit/UIKit.h>

@interface FirstViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

{   
NSArray *sortedCountries;       
}

@property (nonatomic, retain) NSArray *sortedCountries;

@end

In ViewController.m, sortedCountries does this work in -(void)ViewDidLoad{}, storing the result of a sorted .plist.

At

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath {}

called below, sortedCountries returns (null)

Why is the value of sortedCountries not saved? I added retainin the first function ... I think that I do not have a main Objective-C tenant here.

ViewController.m

#import "FirstViewController.h"

@implementation FirstViewController

@synthesize sortedCountries;

-(void)viewDidLoad  {

NSString *path = [[NSBundle mainBundle] pathForResource:@"countries" ofType:@"plist"];  
NSArray *countries = [NSArray arrayWithContentsOfFile:path];
NSSortDescriptor *descriptor = [[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES] autorelease];
NSArray *sortedCountries = [[countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]retain];

}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}

-(NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section {

return 236; 
}

-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath {

NSDictionary *country = [sortedCountries objectAtIndex:indexPath.row];
NSLog(@"countryDictionary is: %@",country);
NSString *countryName = [country objectForKey:@"name"];
NSLog(@"countryName is : %@", countryName);

    static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

if (cell == nil) {

    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                   reuseIdentifier:CellIdentifier] autorelease];

}

cell.textLabel.text = countryName;
return cell;
} 
0
source share
2 answers

You re-declare sortedCountriesas a local variable in viewDidLoad. Using:

sortedCountries = ...

( NSArray *). , , sortedCountries viewDidLoad, viewDidLoad. .

+3
NSArray *sortedCountries = [[countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]]retain];

to

self.sortedCountries = [countries sortedArrayUsingDescriptors:[NSArray arrayWithObject:descriptor]];
+6

Source: https://habr.com/ru/post/1789076/


All Articles