我刚刚进入 Objective-C 并且很早就陷入了困境。我会用我的问题发布代码,但为了保持可读性,我会去掉一些废话,如果你想发布更多代码,请告诉我!
我创建了一个名为“Phrase”的新对象(从 NSObject 子类化),并且正在将 JSON 中的项目读取到这些“Phrase”对象中并将它们添加到数组中。这是第一批代码:
示例 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
从这里我遍历对象并将它们添加到我的拆分视图中的列表中:
- (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
}
希望这很容易理解,如果不是,请告诉我,我会再试一次!