Search code examples
iosobjective-cnsstringnsmutablearraynsobject

-[Person componentsSeparatedByString:]: unrecognized selector sent to instance


I'm new to programming, and I feel a little intimidated posting, and I'm stuck. I don't want a quick fix! Please help me understand this.

I've created a custom method with a name, age, height and gender. It gets called when the NSMutableArray adds custom objects to the array. For some reason I cannot pull said items out of the NSMutableArray. Let's say the age needs to be printed out. I get a error saying...

-[Person componentsSeparatedByString:]: unrecognized selector sent to instance

Person.m

- (id)initWithName:(NSString *)n
            age:(int)a
         height:(float)h
         gender:(char)g
{
self = [super init];
if (self) {
    self.name = n;
    self.age = a;
    self.height = h;
    self.gender = g;
}

    return self;
}

- (NSString *)description
{
NSString *descriptionString = [[NSString alloc] initWithFormat:@"%@, %d, %.1f, %c",
                               self.name,
                               self.age,
                               self.height,
                               self.gender];
NSLog(@"Description String: %@", descriptionString);
    return descriptionString;
}

When adding objects to the NSMutableArray they get converted to a NSString? How do I get the peoples age without the whole strings name and height in the NSLog?

ViewController.m

[self.people addObject:[[Person alloc] initWithName:@"Jake" age:29 height:73.5 gender:'f']];
[self.people addObject:[[Person alloc] initWithName:@"Jerry" age:24 height:82.3 gender:'m']];
[self.people addObject:[[Person alloc] initWithName:@"Jessica" age:29 height:67.2 gender:'f']];

NSString *mystring1 = [self.people objectAtIndex:0];
NSLog(@"%@", mystring1);

// Works
//NSString *list = @"Norm, 42, 73.2, m";

NSArray *listItems = [self.people[0] componentsSeparatedByString:@", "];
NSLog(@"List Items: %@", listItems[1]);// age

Output

Description String: Jake, 29, 73.5, f
Jake, 29, 73.5, f
-[Person componentsSeparatedByString:]: unrecognized selector sent to instance

Solved:

Notice the extra [ age];

int age = [[self.people objectAtIndex:0]age];
NSLog(@"%d", age);

Solution

  • I think the reason it seems like your object is getting converted to a string is this line,

    NSString *mystring1 = [self.people objectAtIndex:0];
    

    You need to specify the property if that is all you want to print

    NSString *nameString = [[self.people objectAtIndex:0]name];