我有类(class)好友
#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:]:值参数为nil'”。谁能告诉我我做错了什么?谢谢!
最佳答案
这个错误非常明显。在调用 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
属性的值。
简单地使用调试器并在单步执行有问题的代码时查看值就可以告诉您所有这些。
关于iphone - 如何创建实例数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18903939/