我有这段代码
SBJsonParser *vol= [[SBJsonParser alloc]init];
if (body) {
NSArray *feeds = [vol objectWithString:body error:nil];
NSDictionary *results = [body JSONValue];
NSArray *subs = [results valueForKey:@"subscriptions"];
NSArray *list;
NSMutableArray *sub;
for (NSDictionary *iscrizione in subs){
NSLog([iscrizione objectForKey:@"title"]);
NSLog([iscrizione objectForKey:@"htmlUrl"]);
list=[NSArray arrayWithObjects:[iscrizione objectForKey:@"title"], [iscrizione objectForKey:@"htmlUrl"], nil];
[sub addObject:list];
}
但是当我尝试将列表添加到NSMutableArray时,程序崩溃了。为什么?
如何插入[iscrizione objectForKey:@"title"]
和[iscrizione objectForKey:@"htmlUrl"]
在数据结构中?
编辑**
SBJsonParser *vol= [[SBJsonParser alloc]init];
if (body) {
NSArray *feeds = [vol objectWithString:body error:nil];
NSDictionary *results = [body JSONValue];
NSArray *subs = [results valueForKey:@"subscriptions"];
NSMutableArray *sub = [[NSMutableArray alloc] initWithCapacity:[subs count]];
for (NSDictionary *iscrizione in subs){
[sub addObject:iscrizione];
}
NSDictionary *it=[[NSDictionary alloc]initWithDictionary:[sub objectAtIndex:0]];
NSLog([it objectForKey:@"title"]);
}
这是我的代码。但我无法理解为什么我不能NSLog [it objectForKey:@“title”]。
答案 0 :(得分:2)
您没有初始化您的NSMutableArray。
应该是
NSMutableArray *sub = [[NSMutableArray alloc] initWithCapacity:[subs count]];
从技术上讲,你可以简单地分配它
NSMutableArray *sub = [[NSMutableArray array];
同样,但这可能更有效率,因为您已经知道将有多少数据条目。
只需注意内存管理,你需要在第一种情况下释放它,并在第二种情况下自动释放它。
答案 1 :(得分:0)
sub
未分配内存。您可以在if条件之外创建一个空数组NSMutableArray *sub = [NSMutableArray array];
,或者在代码中保留一个引用。
答案 2 :(得分:0)
在使用MutableArray之前,您应该alloc
和init
。
SBJsonParser *vol= [[SBJsonParser alloc]init];
if (body) {
NSArray *feeds = [vol objectWithString:body error:nil];
NSDictionary *results = [body JSONValue];
NSArray *subs = [results valueForKey:@"subscriptions"];
NSArray *list;
NSMutableArray *sub = [[NSMutableArray alloc] initWithCapacity:[subs count]];
for (NSDictionary *iscrizione in subs){
NSLog(@"title: %@" ,[iscrizione objectForKey:@"title"]);
NSLog(@"htmlUrl: %@", [iscrizione objectForKey:@"htmlUrl"]);
list=[NSArray arrayWithObjects:[iscrizione objectForKey:@"title"], [iscrizione objectForKey:@"htmlUrl"], nil];
[sub addObject:list];
}
// here you should add code to handle the sub array.
// Do not forget to release the allocated array
[sub release], sub =nil;
}
答案 3 :(得分:0)
以下将正常工作......
NSMutableArray *sub = [[NSMutableArray alloc] init];
for (NSDictionary *iscrizione in subs)
{
NSString *title = [NSString stringWithFormat:@"%@", [iscrizione objectForKey:@"title"]];
NSString *htmlURL = [NSString stringWithFormat:@"%@",[iscrizione objectForKey:@"htmlUrl"]];
list=[NSArray arrayWithObjects:title, htmlURL, nil];
[sub addObject:list mutableCopy];
}