Question

I'm not quite sure how to return a combination of multiple char arrays from a method. In this case I want to return the user's first and last names put together with a space between the two names. Maybe I should just be using NSString...? I'm honestly not really sure.

- (void) setFirstName: (char *) fn andLastName: (char *) ln {

    firstName = fn;
    lastName = ln;
}
- (char *) getFullName {

    return // firstName, " ", and lastName
}
Was it helpful?

Solution

Store the first and last names as NSString properties and convert from char * as soon as possible.

@interface MyObject : NSObject
@property (nonatomic) NSString *firstName;
@property (nonatomic) NSString *lastName;
@property (nonatomic, readonly) NSString *fullName;
@end

@implementation MyObject

...

- (NSString *)fullName {
    return [NSString stringWithFormat:@"%@ %@", self.firstName, self.lastName];
}

@end

// Using code:

char firstName[] = "Mickey";
char lastName[] = "Mouse";

MyObject *o = [MyObject new];

// Old way:
//o.firstName = [NSString stringWithUTF8String:firstName];
//o.lastName = [NSString stringWithUTF8String:lastName];

// New way (thanks to @MartinR for reminding me):
o.firstName = @(firstName);
o.lastName = @(lastName);

NSLog(@"Full name: %@", o.fullName);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top