Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Build a Blog Reader iPhone App Getting Data from the Web Downloading and Parsing JSON Data

"&error" question !

the variable "error" is already a reference to the NSError object ? So it's an address... So why do we use the "&" ?

In the prototype of the method it's says

error:(NSError *)error What means the double * ?

Thank you !

so Amit actually describes what a pointer to a pointer actually does a little incorrectly.
when initialized NSError *error = nil; NSError is actually holding the value 0. When we actually have an error we need to initialize memory in the heap and let NSError point to it. so lets say that we pass in the pointer instead of the pointer to a pointer.

If we pass in just a pointer. In the caller:
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:error];
// NSError will still be 0 here since we pass in by value.

in the callee:
// in the beginning of the code, error = 0
//error occurred
error = [[NSError alloc] initWith....]; // error = [address memory in heap ex:1000]

So in the callee, error becomes pointed to a new memory space in the heap.
But in the caller the error is still pointed to nil.

One way to solve this is to allocated and initialize error in the caller and have the callee modify the object, but that would mean that we allocate space (CPU extensive) every time we need to call this JSONObjectWithData function.

Hopefully that helps.

1 Answer

The main reason why you will need to use & is to pass by reference. Without using &, you will be passing a copy of it. That means that if there is any error, the error is only within the scope of JSONSerialization. The error will not be passed to the NSError *error, since it's a copy rather than a reference. Hope it helps.