Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass and access structures using objective-c

I want to know how to pass structures to another function and subsequently access that structure in the called function. I'm developing for the iPhone and the reason I'm using structs is so that I can eventually pass data as structs to a server being built in C.

Here's the structure:

struct userInfo{
    NSString *firstName;
    NSString *lastName;
    NSString *username;
    NSString *email;
    NSString *ipAddress;
    double latitude;
    double longitude;
};

Here I'm simply fetching some user inputed data along with some CoreLocation data and the iPhone's IP Address:

- (IBAction)joinButton {
    struct userInfo localUser;

    localUser.firstName = firstName.text;
    localUser.lastName = lastName.text;
    localUser.username = username.text;
    localUser.email = emailAddress.text;
    localUser.ipAddress = localIPAddress.text;
    localUser.latitude = currentLocation.coordinate.latitude;
    localUser.longitude = currentLocation.coordinate.longitude;

    [myNetworkConnection registerWithServer:&localUser];
}

function handling the struct:

- (void)registerWithServer:(struct userInfo*)myUser {

    printf("First name is: %s", myUser.firstName);//error when compiling
}

the complier throws this error: request for member 'firstName' in something not a structure or union. Is that struct out of scope when I try to access it in the second function?

like image 444
Eric de Araujo Avatar asked Jun 30 '09 15:06

Eric de Araujo


People also ask

Can you use structs in Objective-C?

You can use regular C structs all you want. Your example tries to put references to an Objective-C object, NSString , into a struct , which is incompatible with ARC. Structs are typically used for simple data structures.

How the Objective-C is working and can you brief the working of structure of Objective-C?

Objective-C arrays allow you to define type of variables that can hold several data items of the same kind but structure is another user-defined data type available in Objective-C programming which allows you to combine data items of different kinds.

How do you declare a struct in Objective-C?

To define a structure in Objective-C, you have to use the struct keyword. The struct statement simply defines a new data type, with more than one member for your Objective-C program. Here is the general form of the struct statement in Objective-C: struct [structure tag] { member definition; member definition; . . .


2 Answers

You are passing in a pointer to a struct. Use the -> operator, not the dot.

myUser->firstName
like image 102
Matt K Avatar answered Sep 30 '22 20:09

Matt K


I can't help but think you should really make that a proper objective-C object with properties - more work but then it'll all behave better and live within the NSObject ecosystem.

like image 25
Kendall Helmstetter Gelner Avatar answered Sep 30 '22 21:09

Kendall Helmstetter Gelner