views:

47

answers:

1

Possible Duplicate:
Basic Objective-C Pointer Question

#import <Foundation/Foundation.h>

BOOL areIntsDifferent( int thing1, int thing2 ) {
 if (thing1 == thing2) {
  return (NO);
 } else {
  return (YES);
 }
}

NSString *boolString (BOOL yesNo) {
 if (yesNo == NO) {
  return( @"NO" );
 } else {
  return( @"YES" );
 }
}

int main (int argc, const char * argv[]) {
    BOOL areTheyDifferent;

 areTheyDifferent = areIntsDifferent (5,5);

 NSLog(@"are %d and %d different? %@", 5, 5, boolString(areTheyDifferent));

 areTheyDifferent = areIntsDifferent (23,42);

 NSLog(@"are %d and %d different? %@", 23, 42, boolString(areTheyDifferent));

    return (0);
}

This is the entire program. It's not terribly complex but it illuminates a common problem that I keep running into - understanding pointers. In this situation, is the return value of the boolString function a pointer because there is no memory allocated to hold a string? And if so, why isn't the areIntsDifferent return value a pointer to a BOOL value? Could I rewrite this program so that the return value of boolString was a string and not a pointer to a string? If so, HOW? I tried to eliminate the * but then I get a compiler error.

A: 

NSString is an object. In Obj-C, objects are always passed around by pointer, never by copying their actual memory.

A BOOL is a primitive. Unlike objects, primitives are passed by value.

Part of the reason for this dichotomy is that primitives are small but objects can be very large (like a UIImage), so passing objects by value would waste a lot of memory. Another reason is that passing objects by pointer allows collections to hold objects of a mixture of different types. E.g. an NSArray can hold a UIImage right next to an NSString and an NSNumber. This is easy for Apple to implement because all of the pointers are the same # of bytes in memory. If the objects were dealt with by value rather than pointer, mixing types in a collection would be very difficult because you would have items of different sizes rather than pointers of uniform size.

Jon Rodriguez