Passing an array into a method

Discussion in 'Mac Programming' started by zcarter, Mar 17, 2008.

  1. zcarter macrumors member

    Apr 21, 2007
    How can I pass an array into a method.

    For example:

    If i had this array..

    array[0] = @"Info";
    array[1] = @"Info2";
    array[2] = @"Info3";

    and I have the method

    - (NSString *)DisplayArray:(NSString *)thevalue

    How could I properly write "thevalue" as declared in the parameter above be set to take in an array?

    What I want out of this is to have the entire array passed into thevalue and to return one piece of the array..

    so like

    return thevalue[2];

    or return the value[0];

    Do you follow me?

    Hope so!

    lemme know - thanks a lot!

    - Zac

  2. Muncher macrumors 65816


    Apr 19, 2007
    I know you're using ObjC, but in C, you would probably want to pass a pointer to the array. I think that would be the simplest way to do it.

    In C this would look like:

    int array[20];
    int* DisplayArray(int *array) {
    There's probably a better way in ObjC, but I don't know that language so... here you go!
  3. zcarter thread starter macrumors member

    Apr 21, 2007

    Thanks for the quick reply...the problem is, I don't know the proper syntax for doing it in Obj. C

  4. antibact1 macrumors 6502

    Jun 1, 2006
    The trick with Objective-C is always to think of things as objects (unless of course there is a great reason not to). There is a nice type, NSArray, that can do exactly what you want.

    @implementation TestClass
    - (id)init
    	self = [super init];
    	NSArray *array = [[NSArray alloc] initWithObjects:@"first", @"second", @"third", nil];
    	[self displayArray:array];
    	return self;
    - (void)displayArray:(NSArray *)anArray
    	NSLog(@"%@", [anArray objectAtIndex:0]);
    	NSLog(@"%@", [anArray objectAtIndex:1]);
    	NSLog(@"%@", [anArray objectAtIndex:2]);
    Edit: There is also the type NSMutableArray that you may want to check out.
  5. zcarter thread starter macrumors member

    Apr 21, 2007

    Thanks a lot for the quick reply!

    Can you also explain to me how NSLog works and what it is with the iPhone?

    - Zac
  6. gnasher729 macrumors P6


    Nov 25, 2005
    It looks like you have an array of NSString*, for example

    NSString* myArray [3];

    You can declare an array as a function parameter either by writing

    NSString* theValues []


    NSString** theValues

    and then you pass myArray as the argument.

    (If you know C, or C++: It is exactly the same as passing an array of pointers in these languages).
  7. zcarter thread starter macrumors member

    Apr 21, 2007
    That sounds easy...

    but when I do

    - (void)DisplayArray : (NSString *)theValues[]

    I get an error...


  8. antibact1 macrumors 6502

    Jun 1, 2006
    Use NSArray or NSMutableArray
  9. antibact1 macrumors 6502

    Jun 1, 2006
    NSLog logs a message to stderr. It is the same thing on the iPhone and logs a message to the console.

    Based on your previous comments, I'm guessing you have no experience developing on OS X and are trying to jump straight to iPhone development. While this sounds like a great idea, you may want to try some straight OS X development first to get familiar with how everything fits together.
  10. zcarter thread starter macrumors member

    Apr 21, 2007
    Great thanks guys!


    One more question, then im set I think..

    I've been trying to save my data, and in order to so you need convert what you have to NSData.

    Apple wrote a function to that for you on their site, however, I cannot convert back from NSData to NSArray..

    Any ideas how?


  11. HiRez macrumors 603


    Jan 6, 2004
    Western US
    You probably wouldn't normally do that in Cocoa. As antibact1 says, you would declare an NSArray object, add your NSString objects into the array, then simply pass the array reference to the function.
    -(void)displayArray:(NSArray*)anArray {
    	NSObjectEnumerator *e = [anArray objectEnumerator];
    	NSString *aString = nil;
    	while (aString = [e nextObject]) {
    		// only do this if you're sure all the objects in your array are valid NSStrings.
    // then to call it, in this case the method was declared in some object called "myController"
    NSArray *myArray = [NSArray arrayWithObjects: @"Info", @"Info2", @"Info3", nil];
    [myController displayArray:myArray];
  12. HiRez macrumors 603


    Jan 6, 2004
    Western US
    You probably want to use NSArchiver and NSUnarchiver (and related classes like NSCoder). NSStrings know how to create themselves from NSData objects, and turn themselves into NSData objects. As well, NSData objects can do the opposite. Just check out the docs for those objects.

    I really would recommend you start by reading through a book to learn Cocoa, though, preferably Aaron Hillegass's.
  13. antibact1 macrumors 6502

    Jun 1, 2006
    If you have written it to a file and want to read it in, you can use [NSArray initWithContentsOfFile:filename]

    Otherwise, try NSKeyedArchiver and NSKeyedUnarchiver
  14. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Because I know very little Obc-C I wanted to try this out, too:

    #import <Foundation/Foundation.h>
    #include "Worker.h"
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
        NSArray *array = [NSArray arrayWithObjects:@"Info",@"Info2",@"Info3", nil];
        NSLog([[Worker DisplayArray:array] objectAtIndex: 1]);
        [pool release];
        return 0;
    #import "Worker.h"
    @implementation Worker
    + (NSArray *)DisplayArray:(NSArray *)thevalues
      NSRange theRange;
      theRange.location = 1;
      theRange.length = 2;
      return [thevalues subarrayWithRange:theRange];
    @interface Worker : NSObject {
    + (NSArray *)DisplayArray:(NSArray *)thevalues;
    I didn't know if you wanted ONE string or a range from the array. One piece is ambiguous. Changes to DisplayArray would be trivial to change to a single NSString * being returned.

  15. zcarter thread starter macrumors member

    Apr 21, 2007
    Yeah I got that part down..

    My two biggest issues now are..

    #1 - I cannot for some reason save my array and read back in from it. (I have now figured out how to properly pass the array as as you can see below, it "Trys" to grab the array and pass it in as a parameter like this: [contentView DisplayArray: read])

    My code is as follows:
    	//Write into File Example
    	NSArray *thenew = [[NSArray alloc] initWithObjects:@"first", @"second", @"third", nil];
    	[thenew writeToFile:@"Test.txt" atomically:NO];
    	//Read from the file example
    	NSArray *read;
    	[read initWithContentsOfFile:@"Test.txt"];
    	//Display the Label
    	[contentView DisplayArray:read];
    As you can is supposed to be read in from the same file (Im assuming it doesn't matter the name of the file? Also..does it auto create the file if its not there? Where Can i view these files once they have been written.

    And Simply #2...

    How do you use NSLog?


    Your help is always appreciated...
  16. kainjow Moderator emeritus


    Jun 15, 2000
    initWithContentsOfFile: is a method you use on an instance of NSArray. You have not yet created a new instance of NSArray. So your code should look like this:

    NSArray *read = [[NSArray alloc] initWithContentsOfFile:@"Test.txt"];
    NSLog() formats strings and writes it to the standard output. For example:

    NSString *name = @"Bobby";
    int age = 15;
    NSLog(@"Hello there, %@. You are %d years old.", name, age);
    Which would output to the console:

    Check out String Format Specifiers for more ways on how you can use other data types with NSLog() (and other similar methods).

Share This Page