Я только что прыгнул в Objective-C и застрял довольно рано. Я опубликую код с моим вопросом, но чтобы он был читабельным, я избавлюсь от некоторой чуши, дайте мне знать, если вы хотите, чтобы больше кода было опубликовано!
Я создал новый объект под названием «Фраза» (подкласс из NSObject), и я читаю элементы из JSON в эти объекты «Фраза» и добавляю их в массив. Вот первая партия кода:
Пример JSON:
{
"phrases": [
{
"title": "Title of my Phrase",
"definition" : "A way to look at some words",
"location" : "Irish Proverb"
}
]
}
Скрипт, в котором я читаю это:
- (void)viewDidLoad {
[super viewDidLoad];
self.phraseDictionary = [[NSMutableArray alloc] initWithObjects:nil];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"phrase" ofType:@"json"];
NSString *myRawJSON = [[NSString alloc] initWithContentsOfFile:filePath];
NSData *jsonData = [myRawJSON dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary *entries = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:nil];
for (id key in entries) {
NSObject *phrases = [entries objectForKey:key];
for (id phrase in phrases) {
Phrase *pushArrayToPhrase = [[Phrase alloc] initWithText:[phrase objectForKey:@"title"] definition:[phrase objectForKey:@"definition"] location:[phrase objectForKey:@"location"]];
[self.phraseDictionary addObject:pushArrayToPhrase];
}
}
}
Файл фразы m:
#import "Phrase.h"
@implementation Phrase
@synthesize title;
@synthesize definition;
@synthesize location;
- (id)init {
self = [super init];
if (self != nil) {
title = @"";
definition = @"";
location = @"";
}
return self;
}
- (id)initWithTitle:(NSString *)tit definition:(NSString *)def location:(NSString *)loc {
self = [super init];
if (self != nil) {
title = tit;
definition = def;
location = loc;
}
return self;
}
@end
Отсюда я перебираю объекты и добавляю их в список в моем splitview:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"CellIdentifier";
// Dequeue or create a cell of the appropriate type.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
cell.accessoryType = UITableViewCellAccessoryNone;
}
Phrase *cellPhrase = [self.phraseDictionary objectAtIndex:indexPath.row];
cell.textLabel.text = cellPhrase.title;
return cell;
}
Но когда я щелкаю по элементу и запрашиваю фразу, основанную на indexPath.row одного клика, я могу получить доступ только к свойству, используемому в cell.textLabel.text. Любая другая попытка получить доступ к свойству объекта Phrase с этого момента завершается с симулятора.
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
Phrase *cellPhrase = [self.phraseDictionary objectAtIndex:indexPath.row];
detailViewController.detailItem = cellPhrase;
//If i attempt 'cellPhrase.definition' here, the app will close without an error
}
Надеюсь, за этим легко последовать, дайте мне знать, если это не так, и я попробую еще раз!