在完成块内完成操作后没有得到结果

时间:2013-12-16 06:36:40

标签: ios

这是我的解析器类,在解析了具有对象数组的json url之后,这个类工作得很好。

@interface parseOperation : NSOperation
@property (nonatomic, copy) void (^errorHandler)(NSError *error);

@property (nonatomic, strong, readonly) NSMutableArray *appRecordList;

- (id)initWithData:(NSData *)data;
@end

#import "parseOperation.h"

@interface parseOperation () <NSURLConnectionDataDelegate>
{
NSMutableArray *array;
NSMutableData *mdata;
NSURLConnection *conn;

//  NSMutableArray *arrone;

}
@property (nonatomic, strong) NSMutableArray *appRecordList;
@property (nonatomic, strong) NSData *dataToParse;
@property (nonatomic, strong) NSMutableArray *workingArray;
@property (nonatomic, strong) Jobs *workingEntry;
@property (nonatomic, strong) NSMutableString *workingPropertyString;
@property (nonatomic, strong) NSArray *elementsToParse;
@property (nonatomic, readwrite) BOOL storingCharacterData;
@end

@implementation parseOperation
- (id)initWithData:(NSData *)data
{
self = [super init];
if (self != nil)
{
    _dataToParse = data;

}
return self;
}
- (void)handleError:(NSError *)error
{
    NSString *errorMessage = [error localizedDescription];
   UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Cannot Show Top Paid Apps.........."
                                                          message:errorMessage
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
[alertView show];
}

- (void)main
{
    //self.workingArray = [NSMutableArray array];
    self.workingPropertyString = [NSMutableString string];
    self.workingArray=[[NSMutableArray alloc]init];

NSDictionary *allData=[NSJSONSerialization JSONObjectWithData:_dataToParse options:0 error:nil];

for (NSDictionary *dict in allData)
{

    self.workingEntry =[[Jobs alloc]init];
    self.workingEntry.title=[dict objectForKey:@"title"];

   [self.workingArray addObject:self.workingEntry];


    self.workingEntry=nil;

}
    if (![self isCancelled])
{

    self.appRecordList = [NSMutableArray arrayWithArray:self.workingArray];

    NSLog(@"self.appRecordList======== %@", self.appRecordList);
    NSLog(@"parse complete......");

}

   // self.workingArray = nil;
self.workingPropertyString = nil;
self.dataToParse = nil;
}


@end

这里我得到解析后的结果,self.appRecordList数组显示正确的结果,但我的问题是当iam尝试从具有空值的appdelegate访问数组时。

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
UINavigationController *nav;

}

@property (strong, nonatomic) UIWindow *window;

@property (nonatomic, strong) NSMutableArray *entries;

@end



#import "AppDelegate.h"
static NSString *const TopPaidAppsFeed =@"http:url";


@interface AppDelegate ()
@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, strong) NSOperationQueue *queue1;
@property (nonatomic, strong) NSURLConnection *appListFeedConnection;
@property (nonatomic, strong) NSMutableData *appListData;

@end



@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURLRequest *urlRequest   = [NSURLRequest requestWithURL:[NSURL URLWithString:TopPaidAppsFeed]];
self.appListFeedConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];

NSAssert(self.appListFeedConnection != nil, @"Failure to create URL connection.");

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;


return YES;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.appListData = [NSMutableData data]; 
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
 [self.appListData appendData:data];  // append incoming data
}


 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

    if ([error code] == kCFURLErrorNotConnectedToInternet)
    {

        NSDictionary *userInfo = [NSDictionary dictionaryWithObject:@"No Connection Error"
                                                         forKey:NSLocalizedDescriptionKey];
    NSError *noConnectionError = [NSError errorWithDomain:NSCocoaErrorDomain
                                                     code:kCFURLErrorNotConnectedToInternet
                                                 userInfo:userInfo];
    [self handleError:noConnectionError];
}
else
{
    // otherwise handle the error generically
    [self handleError:error];
}

self.appListFeedConnection = nil;   // release our connection
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.appListFeedConnection = nil;   // release our connection

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

// create the queue to run our ParseOperation
self.queue = [[NSOperationQueue alloc] init];

// create an ParseOperation (NSOperation subclass) to parse the RSS feed data
// so that the UI is not blocked
parseOperation *parser = [[parseOperation alloc] initWithData:self.appListData];

parser.errorHandler = ^(NSError *parseError) {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self handleError:parseError];
    });
};

// Referencing parser from within its completionBlock would create a retain
// cycle.
__weak parseOperation *weakParser = parser;

parser.completionBlock = ^(void) {
    if (weakParser.appRecordList) {
        // The completion block may execute on any thread.  Because operations
        // involving the UI are about to be performed, make sure they execute
        // on the main thread.
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"completionBlock");

            NSLog(@"weakParser.appRecordList====%@", weakParser.appRecordList);//null

            self.entries=[[NSMutableArray alloc]init];
            self.entries = weakParser.appRecordList;
                            NSLog(@"self.entries====%@", self.entries);//null
            NSLog(@"weakParser.appRecordList====%@", weakParser.appRecordList);

        });
    }

    // we are finished with the queue and our ParseOperation
    self.queue = nil;
};

[self.queue addOperation:parser]; // this will start the "ParseOperation"

// ownership of appListData has been transferred to the parse operation
// and should no longer be referenced in this thread
self.appListData = nil;
}

@end

在此完成块内,weakParser.appRecordList显示null,请帮助。这是我的输出屏幕enter image description here

1 个答案:

答案 0 :(得分:0)

您可以尝试删除完成块中的dispatch_async(dispatch_get_main_queue()......,然后执行

if (weakParser.appRecordList) {
        self.entries=[[NSMutableArray alloc]init];
        self.entries = weakParser.appRecordList;
}

看看它是否有效