作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图掌握如何在 Objective C 中使用 block 。在我编写的这个简单的应用程序中,我获得了一组图像作为 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 block ,而是直接跳转到 return 语句。
谁能告诉我如何纠正这个问题?
我创建了一个项目来展示我面临的问题并上传了它 here如果你想快速浏览一下。
谢谢。
最佳答案
问题在于
NSDictionary *dict = responseObject[@"Images"];NSArray *arr = [dict allValues];
responseObject[@"图片"];返回一个 NSArray 类。因此,将您的命令更改为 NSArray 类。并枚举那个“dict”对象。你不需要你的对象。
关于ios - 无法从 JSON 流中检索对象以进行枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21118594/
我是一名优秀的程序员,十分优秀!