0

过去一小时我一直在尝试解决这个问题,但仍然没有运气

我有一个 NSMutableArray 实例变量,它保存以下类中的对象:数组成功填充到我填充它的方法中,但它在所有其他方法/类中显示为空

.h 文件...

#import "RedditPostItem.h"

@interface RedditRepository : NSObject

@property (nonatomic, strong) NSMutableArray *redditPosts; //<<** this
is the problem array

@property (nonatomic, strong,readwrite) NSDictionary *allJSONData;
@property (nonatomic, strong,readwrite) NSMutableData *incomingData;


- (void)getPosts;
- (void)printAllTitles;

@end

.m 文件

@implementation RedditRepository . . @synthesize
redditPosts=_redditPosts;

. .

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {


    self.redditPosts = [[NSMutableArray alloc] initWithCapacity:20];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    //parse json data

    _allJSONData = [NSJSONSerialization JSONObjectWithData:_incomingData options:0 error:nil];

    NSDictionary *dataDictionary = [_allJSONData objectForKey:@"data"];

    NSArray *arrayOfChildren = [dataDictionary objectForKey:@"children"];


    for (NSDictionary *diction in arrayOfChildren) {

        NSDictionary *childrenData = [diction objectForKey:@"data"];


        RedditPostItem *postItem = [[RedditPostItem alloc]initWithAPIResponse:childrenData];

       //******************************* add to array..... 

        [self.redditPosts addObject:postItem];



    }

    //******* if i iterate through 'self.redditPosts' i can see everything uptill this point and the array successfully gets
populated//

}

//********* if I execute any operation from any other method in this
class or any other class...the array shows up as empty!!***//

- (void)printAllTitles{

     if(self.redditPosts == nil) {

    NSLog(@"array is empty.....");   ///always shows up as empty for some reason<<<<<< }

     }
4

1 回答 1

2

您的数组正在异步填充 - 您在后台从 URL 下载,而您的用户界面继续在前台运行。您将其视为空的原因是它尚未填充。您的应用程序应该以这样一种方式编写,即它可以处理无法立即获得的数据,并且能够在数据可用时自行更新。

如果这不能让您走上正轨,请就您要解决的问题提出更具体的问题。

于 2013-09-01T02:58:48.743 回答