2

我有班级朋友

#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 parameter is nil'”。谁能告诉我我做错了什么?谢谢!

4

1 回答 1

5

错误很明显。在您对您的调用中,NSJSONSerialization dataWithJSONObject:options:error:您将传递nil给第一个参数。

你有:

NSData *jsonAr = [NSJSONSerialization dataWithJSONObject:ar options:NSJSONWritingPrettyPrinted error:nil];

这意味着arnil

因为你得到ar如下:

NSArray *ar = [JSON valueForKey:@"response"];

这意味着JSON(无论是什么)是nil或它对response财产没有价值。

简单地使用调试器并在您逐步执行有问题的代码时查看值会告诉您所有这些。

于 2013-09-19T20:09:33.157 回答