Question

I have a NSArray as a result of a web service (JSON) request.

If I print NSLog("%@", jsonResult) the Array it shows up correctly:

(
        {
            text = “Some text”;
            coordinates = “11.333345 - 09.33349”;
        }

        {
            text = “Some text2”;
            coordinates = “11.333345 - 09.33349”;
        }

        {
            text = “Some text3”;
            coordinates = “11.333345 - 09.33349”;
        }

        …
)

But If I try to access the value of the key "text" of each entry within the NSArray with my following function, I always get an output like this:

Text )r'ì• (instead of "Some text2, 3 ....")

So I think there is a mismatch of types, but I don't know how to figure out where the problem is. In Objective-C it works very well.

func getResult(){
        self.webService.getResult({ jsonResult in

            jsonResult!.enumerateObjectsUsingBlock({ object, index, stop in
                var txt : NSString = object.valueForKey("text") as NSString
                NSLog("Text %s", txt)

            })

            NSLog("Ready %@", jsonResult!)

        });
    }

Any ideas what's going wrong?

UPDATE 1

I figured out, that if I just use NSObject instead of NSString it displays the text correct

var txt : NSObject = object.valueForKey("text") as NSObject
NSLog("%@", txt)

But anyway, I have to cast that NSObject object to NSString or String, to display...

Which encoding is it expecting to display the string...or how to cast this NSObject????

Was it helpful?

Solution

var txt : NSString = object.valueForKey("text") as NSString
NSLog("Text %s", txt)

The problem is the %s format specifier, which is for C-style strings. You need %@, which is for objects.

In Swift, it's recommended to use println(), which does away with format strings altogether:

var txt : NSString = object.valueForKey("text") as NSString
println("Text \(txt)")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top