2012-08-07 40 views
0

我工作的一个网站订阅应用程序的iPhone,除其他事项外,确定是否图像连接到一个帖子,并将其存储在一个数组。当我运行代码时,我的NSLog告诉我没有任何东西被放入数组,即使它正在读取是否存在objectAtKey:@“图片”。以下是我的一些代码。的iOS:无法将一个字符串存储在数组中

从MasterView.m:

//create array containing individual "datas" 
NSArray *items = [json objectForKey:@"data"]; 

for(NSDictionary *item in items) 
{ 
    // store message in ItemStore sharedStore 
    if([item objectForKey:@"message"] || [item objectForKey:@"message"] != nil || 
     [[item objectForKey:@"message"] length] > 0){ 
     [[JSONFeedItemStore sharedStore] createItem:[item objectForKey:@"message"]]; 
    } 

    // 
    if([item objectForKey:@"picture"]){ 
     [[JSONFeedItemStore sharedStore] createPicture:[[item objectForKey:@"picture"] description]]; 
     NSLog(@"url: %@", [item objectForKey:@"picture"]); 
    } else { 
     [[JSONFeedItemStore sharedStore] createPicture:@"http://i.imgur.com/TpIK5.png"]; // blank 
     NSLog(@"creating blank picture"); 
    } 
} 

从ItemStore.m

- (void)createPicture:(NSString *)pictureUrl 
{ 
    [pictures addObject:pictureUrl]; 
    NSLog(@"Number: %d, URL: %@", [pictures count], [pictures objectAtIndex:[pictures count]]); 
} 

和我的控制台

2012-08-07 08:21:54.153 JSONFeed[2502:f803] Number: 0, URL: (null) 
2012-08-07 08:21:54.154 JSONFeed[2502:f803] creating blank picture 
2012-08-07 08:21:54.155 JSONFeed[2502:f803] Number: 0, URL: (null) 
2012-08-07 08:21:54.156 JSONFeed[2502:f803] creating blank picture 
2012-08-07 08:21:54.157 JSONFeed[2502:f803] Number: 0, URL: (null) 
2012-08-07 08:21:54.157 JSONFeed[2502:f803] url: http://photos-a.ak.fbcdn.net/hphotos-ak-ash4/423482_427478620624383_82270372_s.jpg 
2012-08-07 08:21:54.158 JSONFeed[2502:f803] Number: 0, URL: (null) 
2012-08-07 08:21:54.158 JSONFeed[2502:f803] creating blank picture 

SharedStore是创建存储消息的ItemStore类的一部分和来自Facebook帖子的图片。如果您有任何问题,或需要查看更多代码,请随时询问。我也正在采取任何改进建议,因为我对编程应用程序仍然很陌生。

+0

当你去调用'createPicture'你为什么要送吧'[[项目objectForKey:@ “图片报”]描述]',而不是仅仅'[项目objectForKey:@ “图片报”]'? – 2012-08-07 13:30:29

+0

额外括号是因为我正在调用该对象的描述。其余的调用是[[item objectForKey:@“picture”] description]。 – Chance 2012-08-07 13:37:57

+0

我知道为什么额外支架存在,但为什么使用'description'? – 2012-08-07 13:38:45

回答

3

一种可能性是,pictures为零。如果数组不存在,则不能将对象添加到数组,并且将消息发送到nil是合法的。您返回的结果也将为零或零,因此您拨打-objectAtIndex:的电话记录“(空)”。

+0

谢谢你,迦勒。我绝对在这个上做了一个大一的错误!忘记初始化阵列。 – Chance 2012-08-07 13:43:03

3

其一,当你做这样的事;

[array objectAtIndex:[array count]]; 

你会得到一个nil对象,因为根据定义objectAtIndex:array.count超出了数组的边界,因为在编程所有的数组是0索引

你需要的是

[array objectAtIndex([array count]-1)]; 
+0

或者你可以使用[数组lastObject],它更易于阅读 – 2012-08-07 13:35:27

+0

@Dan F,虽然你的回答并不是问题的实际解决方案,但它确实指出了我的代码中存在缺陷,所以我对它进行了升级。谢谢您的帮助! – Chance 2012-08-07 19:38:51

相关问题