我有班级朋友
#import "Friend.h"
#import "AFJSONRequestOperation.h"
#import "UIImageView+AFNetworking.h"
#import "AFHTTPClient.h"
@implementation Friend
-(id)init {
self = [super init];
return self;
}
-(id)initWithSecret:(NSString *)theSecret
userId:(NSString *)theUserId {
self = [super init];
if(self) {
secret = theSecret;
user_id = theUserId;
/// get friends
NSString *str = [NSString stringWithFormat:@"https://api.vk.com/method/friends.get?fields=first_name,last_name&uid=%@&access_token=%@", user_id, secret];
NSURL *url = [[NSURL alloc] initWithString:str];
NSURLRequest *friendRequest = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *friendOperation = [AFJSONRequestOperation JSONRequestOperationWithRequest:friendRequest success:^(NSURLRequest *friendRequest, NSHTTPURLResponse *response, id JSON) {
//converting to array
NSArray *ar = [JSON valueForKey:@"response"];
NSData *jsonAr = [NSJSONSerialization dataWithJSONObject:ar options:NSJSONWritingPrettyPrinted error:nil];
friendsAr = [NSJSONSerialization JSONObjectWithData:jsonAr options:NSJSONReadingMutableContainers error:nil ];
self.firstName = [friendsAr valueForKey:@"first_name"];
self.lastName = [friendsAr valueForKey:@"last_name"];
self.uid = [friendsAr valueForKey:@"uid"];
} failure:^(NSURLRequest *friendRequest, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];
[friendOperation start];
}
return self;
}
@end
在我的ViewController中,我可以创建一个类似的实例:
self.myFriend = [[Friend alloc] initWithSecret:self.secret userId:self.user_id];
它工作正常,但是当我尝试创建一个数组时:
NSMutableArray *persons = [NSMutableArray array];
for (int i = 0; i < 165; i++) {
self.myFriend = [[Friend alloc] initWithSecret:self.secret userId:self.user_id];
[persons addObject: self.myFriend];
}
self.arrayOfPersons = [NSArray arrayWithArray:persons];
它因错误而崩溃:“因未捕获的异常而终止应用程序'NSInvalidArgumentException',原因:' * + [NSJSONSerialization dataWithJSONObject:options:error:]:value参数为nil'”。谁能告诉我我做错了什么?谢谢!
答案 0 :(得分:5)
错误很清楚。在致电NSJSONSerialization dataWithJSONObject:options:error:
时,您将nil
传递给第一个参数。
你有:
NSData *jsonAr = [NSJSONSerialization dataWithJSONObject:ar options:NSJSONWritingPrettyPrinted error:nil];
这意味着ar
为nil
。
由于您获得ar
如下:
NSArray *ar = [JSON valueForKey:@"response"];
这意味着JSON
(无论是什么)是nil
还是response
属性没有价值。
简单地使用调试器并在逐步查看违规代码时查看值会告诉您所有这些。