Domanda

This is the code I am using to get string coming through a SBJson parsing:

NSMutableArray *abc=[jsonData valueForKey:@"items"];

NSString *imgStr=(NSString *)[abc valueForKey:@"image"];
NSLog(@"%@",imgStr);

here abc is NSMutableArray

and the exception it is throwing is

> -[__NSArrayI stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance
È stato utile?

Soluzione

In the first line you declare abc to be an NSMutableArray

In the second line you attempt to access it as an NSDictionary.

In your case (and I am guessing here), I expect you have an array of items, and each item is a dictionary with an "image" key.

So to get your first item you might use

  NSDictionary* firstItem = [abc objectAtIndex:0];

Then you can extract your image from that:

NSString *imgStr=(NSString *)[firstItem valueForKey:@"image"];1

 NSString *imgStr = [abc objectForKey:@"image"];

1 see comment from @Stig

Altri suggerimenti

Your code has several problems:

  1. For NSArray, valueForKey: returns another array. It does not return an NSString, regardless of your cast. You need get a reference to the first entry in the array, then call objectForKey: on that.

  2. You're using the NSKeyValueCoding method valueForKey: where you're probably intending to use the NSDictionary method objectForKey:. For dictionaries they are roughly interchangeable, but if you'd used objectForKey: you would have got an easy to understand error about not being able to call objectForKey: on an array. Use valueForKey: only when you really want key-value-coding semantics.

  3. You almost never need to cast id in Objective-C. You're only hiding errors that way. (It may or may not be hiding your problem in this instance, but it's certainly uglier, incorrect (because you're trying to cast an array to a string) and just fooling you into thinking you have a string because the cast didn't fail.)

You probably meant to write something like this:

NSArray *abc = [jsonData valueForKey:@"items"];
NSDictionary *entry = [abc objectAtIndex:0];    
NSString *imgStr = [entry objectForKey:@"image"];
NSLog(@"%@", imgStr);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top