NSMutableArray不保留方法之外的值

时间:2013-09-01 02:27:31

标签: objective-c nsmutablearray

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

我有一个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<<<<<< }

     }

1 个答案:

答案 0 :(得分:2)

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

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