How do you get and set a class property across multiple functions in Objective-C?

Posted by editor on Stack Overflow See other posts from Stack Overflow or by editor
Published on 2010-05-05T06:09:51Z Indexed on 2010/05/05 6:18 UTC
Read the original article Hit count: 119

Filed under:
|
|

Following up on this question about sharing objects between classes, I now need to figure out how to share the objects across various functions in a class.

First, the setup: In my App Delegate I load menu information from JSON into a NSMutableDictionary and message that through to a view controller using a function called initWithData. I need to use this dictionary to populate a new Table View, which has methods like numberOfRowsInSection and cellForRowAtIndexPath.

I'd like to use the dictionary count to return numberOfRowsInSection and info in the dictionary to populate each cell. Unfortunately, my code never gets beyond the init stage and the dictionary is empty so numberOfRowsInSection always returns zero.

I thought I could create a class property, synthesize it and then set it. But it doesn't seem to want to retain the property's value. What am I doing wrong here?

In the header .h:

@interface FirstViewController:UIViewController <UITableViewDataSource, UITableViewDelegate, UITabBarControllerDelegate> {
 NSMutableDictionary *sectorDictionary;
 NSInteger sectorCount;
}

@property (nonatomic, retain)  NSMutableDictionary *sectorDictionary;

- (id)initWithData:(NSMutableDictionary*)data;

@end

in the implementation .m:

- (id) testFunction:(NSMutableDictionary*)dictionary {
 NSLog(@"Count #1: %d", [dictionary count]);

 return nil;
}

- (id)initWithData:(NSMutableDictionary *)data {

 if (!(self=[super init])) {
  return nil;
 }

 [self testFunction:data];

 // this is where I'd like to set a retained property
 self.sectorDictionary = data;

 return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
 NSLog(@"Count #2: %d", [self.sectorDictionary count]);
 return [self.sectorDictionary count];
}

Output from NSLog:

2010-05-04 23:00:06.255 JSONApp[15890:207] Count #1: 9
2010-05-04 23:00:06.259 JSONApp[15890:207] Count #2: 0

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about iphone