How to use NSJSONSerialization

后端 未结 12 771
天涯浪人
天涯浪人 2020-11-22 08:38

I have a JSON string (from PHP\'s json_encode() that looks like this:

[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]
         


        
12条回答
  •  眼角桃花
    2020-11-22 09:21

    The issue seems to be with autorelease of objects. NSJSONSerialization JSONObjectWithData is obviously creating some autoreleased objects and passing it back to you. If you try to take that on to a different thread, it will not work since it cannot be deallocated on a different thread.

    Trick might be to try doing a mutable copy of that dictionary or array and use it.

    NSError *e = nil;
    id jsonObject = [NSJSONSerialization 
    JSONObjectWithData: data 
    options: NSJSONReadingMutableContainers 
    error: &e] mutableCopy];
    

    Treating a NSDictionary as NSArray will not result in Bad access exception but instead will probably crash when a method call is made.

    Also, may be the options do not really matter here but it is better to give NSJSONReadingMutableContainers | NSJSONReadingMutableContainers | NSJSONReadingAllowFragments but even if they are autoreleased objects it may not solve this issue.

提交回复
热议问题