【发布时间】:2014-01-14 16:26:28
【问题描述】:
我正在尝试了解如何在 Objective C 中使用块。在我正在编写的这个简单应用程序中,我将一组图像作为 JSON 流。我正在尝试将图像取出并将它们客观化,然后将它们收集到NSMutableArray 中。下面是我的代码
WebImage.h
#import <Foundation/Foundation.h>
@interface WebImage : NSObject <NSCopying>
@property (strong, nonatomic) NSString *imageId;
@property (strong, nonatomic) NSString *imageName;
@property (strong, nonatomic) NSString *imagePath;
- (id)initWithId:(NSString *)imageId andName:(NSString *)imageName andPath:(NSString *)imagePath;
+ (NSArray *)retrieveAllImages;
@end
WebImage.m
#import "WebImage.h"
#import "AFNetworking.h"
#define HOST_URL @"http://toonmoodz.osmium.lk/"
@implementation WebImage
#pragma mark - NSCopying
- (id)copyWithZone:(NSZone *)zone
{
WebImage *newImage = [WebImage new];
newImage.imageId = self.imageId;
newImage.imageName = self.imageName;
newImage.imagePath = self.imagePath;
return newImage;
}
- (id)initWithId:(NSString *)imageId andName:(NSString *)imageName andPath:(NSString *)imagePath
{
if (self = [self init]) {
self.imageId = imageId;
self.imageName = imageName;
self.imagePath = imagePath;
}
return self;
}
+ (NSArray *)retrieveAllImages
{
NSMutableArray *images = [[NSMutableArray alloc] init];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:[NSString stringWithFormat:@"%@%@", HOST_URL, @"All_Images.php"] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dict = responseObject[@"Images"];
NSArray *arr = [dict allValues];
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *image = obj;
NSLog(@"%@", image);
[images addObject:[[WebImage alloc] initWithId:[image objectForKey:@"id"]
andName:[image objectForKey:@"name"]
andPath:[image objectForKey:@"image"]]];
}];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error in image retrieveing: %@", error.localizedDescription);
}];
return [images copy];
}
传入的 JSON 流如下所示
{
Images = (
{
createddate = "2014-01-08 12:20:24";
id = 1;
image = "images/Rock_1.png";
isEnabled = 1;
name = "Rock_1";
},
{
createddate = "2014-01-08 15:12:26";
id = 2;
image = "images/Rock_2.png";
isEnabled = 1;
name = "Rock_2";
}
);
}
我的问题是我无法从 JSON 字符串中检索图像对象。当我调试时,编译器甚至没有进入retrieveAllImages方法中的GET块,而是直接跳转到return语句。
谁能告诉我如何纠正这个问题?
我创建了一个项目来展示我所面临的问题,如果你想快速浏览一下,我已经将它上传到here。
谢谢。
【问题讨论】:
-
您是否尝试在
GET块内部设置断点?我认为如果您从外部接近它们,调试器会跳过这些块。 -
我刚试过,但没有。它仍然会跳过该块。
-
也不进入故障块?
-
不。只是跳转到最后的return语句。
-
上面的dump其实是一个代表JSON的NSDictionary的dump。显然,OP 至少正确接收了一次 JSON,并且能够解析它。
标签: ios json nsdictionary objective-c-blocks afnetworking-2