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);
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];
You can't perform componentsSeparatedByString on your Person object since it's not a string and doesn't have that method. (NSMutableArray objects are not automatically converted to NSStrings.) But to get the age of your Person, should be fairly simple anyway. Just access Person's age property:
int age = self.people[0].age;
NSLog(#"Age: %d", age);
Edit: You can technically use componentsSeparatedByString on your mystring1 NSString, like so:
NSArray *listItems = [mystring1 componentsSeparatedByString:#", "];
NSLog(#"List Items: %#", listItems[1]);// age
But again, I don't see the point of doing this when you can access the Person's age property directly.
The componentsSeparatedByString method is an instance method of NSString class. You can't call it on your Person class in this way.
I don't know why you need that code, if you are trying to access age, then:
NSLog(#"Age %d", self.people[0].age);
is enough. If you are trying to achieve any other thing, then you can get the components like:
NSArray *listItems = [self.people[0].description componentsSeparatedByString:#", "];
NSLog(#"List Items: %#", listItems[1]);// age
One would think this would work; however, I can not call .age on my array.
NSLog(#"Age %d", self.people[0].age);
Gives the following output...
Property 'age' not found on object of type 'id'
One would also think componentsSeparatedByString would work. It doesn't split my string by the comma and gives an error.
-[Person componentsSeparatedByString:]: unrecognized selector sent to instance
Solved READ UP
I think you are getting confused about why when you log the object you are getting a string, but you can't perform any methods on it.
And here is why you think you are getting a string, you've implemented the description property, which comes from the NSObject protocol. When you do a log of an object with a %# parameter you are getting the result of this property, which is a string.
So looking at your code:
NSString *mystring1 = [self.people objectAtIndex:0]; //1
NSLog(#"%#", mystring1); //2
The first thing is that you are getting the first object out of your array. objectAtIndex returns an id, which is a pointer to an NSObject. It is not a strongly typed return. You are allocating it to an NSString which is wrong, because it as actually a person object. But since you aren't calling any NSString methods on it, the compiler is not flagging this incorrect assignment.
The second thing is that you are just getting the result of the description property, as I've already mentioned.
Your edited solution:
int age = [[self.people objectAtIndex:0]age];
Works, but here is why: you are getting the objectAtIndex:0 which returns an id. Then you are sending it the message age. Objective-C is a dynamic language, which means you can send any message to any object (although you get a run-time crash if the object does not implement the method) In this case, your Person object does implement an age method (since it's a public property) so you get an age back.
A different way of doing it:
NSInteger age;
Person *person = self.people.firstObject;
if (person) {
age = person.age;
} else {
age = NSNotFound;
}
Why am I doing it this way?
Firstly, I am getting the firstObject out of the array and putting it into a typed variable. This is safer, as if there is no object at index 0 (i.e. the array is empty) then you won't crash your app. firstObject returns the first object if it exists, on a nil if it doesn't.
Secondly, Only if the person has been correctly extracted from the array, do I assign the age to an NSInteger variable. You should prefer the specific types of NSInteger over int (and CGFloat over float) because they will use the correctly sized variable when running on 32-bit or 64-bit` systems.
Thirdly, if person cannot be created I am assigned the value of NSNotFound to the age. This is a typedef for a very large number, one that you can compare against. Just returning 0 in age is not enough to tell you there was an error. The person could have an age of 0. with this code you can test the age with:
if (age != NSNotFound) {
// This is a valid age, do something with it
} else {
// A person object could not be extracted from the array, this is not a valid age
}
Is this overkill? Not really. When you start writing real, complex apps, this sort of defensive programming will come naturally to you. Arrays can be empty, your data could be incorrectly created, etc. Writing code that gracefully handles these eventualities is the real skill of programming. Unfortunately, It's a bit more long winded, and most tutorials that you find on the web show you the simple, happy path.
I hope this gives you a better idea of what your code is doing and what more you could be doing to write robust code.
Related
i tried this, this and this link
I have an array (Say personObjectArray) which contains objects of class Person.
Class Person having 2 variables say,
NSString *name, NSString *age.
Here age has type of nsstring.
Now when i sort like below,
personObjectArray = [[personObjectArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){
return [p1.age compare:p2.age];
}] mutableCopy];
It sorts like this,
1,
11,
123
2,
23,
3... It sorts like alphabetical order not considering it as an number.
So i change my code like this,
personObjectArray = [[personObjectArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){
return [[p1.age intValue] compare:[p2.age intValue] ];
}] mutableCopy];
And it says, Bad receiver type 'int'
How can i sort now ?
Please don't tell me to change the datatype of age in Person class. I can't change it. Any help appreciated (: , Thanks for the time.
You were using compare on a primitive (Not Object) type int , hence it won't work.
Try this
return [#([p1.age intValue]) compare:#([p2.age intValue])];
Here, we are using NSNumber (Which is an object type) to compare the int values
#() is a NSNumber's literal
Hope this will help you.. (:
Try this :
personObjectArray = [[personObjectArray sortedArrayUsingComparator:^NSComparisonResult(Person *p1, Person *p2){
return [p1.age compare:p2.age options:NSNumericSearch];
}] mutableCopy];
So unlike C where an array = &array = &array[0], was trying to have a quick look at the structure of a NSArray and how its objects were stored and have a question with the below code.
NSString *str1 = [NSString stringWithFormat:#"abc"];
NSString *str2 = [NSString stringWithFormat:#"xyz"];
NSString *str3 = [NSString stringWithFormat:#"123"];
NSMutableArray *someArray = (NSMutableArray*)#[#"1",#"2",#"3"];
NSMutableArray *original = (NSMutableArray*)#[str1, str2, [someArray mutableCopy]];
NSMutableArray *deep = [original mutableCopy];
[[original objectAtIndex:2] addObject:str3];
for (id obj in original) {
NSLog(#"\nIn Original:: \nvalue is:%#, at :%p; Address of object: %p\n",obj, obj, &obj);
}
for (id obj in deep) {
NSLog(#"\nIn Deep:: \nvalue is:%#, at :%p; Address of object: %p\n",obj, obj, &obj);
}
NSLog(#"\n Address of Original : %p \n", &original);
NSLog(#"\n Address IN Original : %p \n", original);
NSLog(#"\n Address in first object of original : %p \n", [original objectAtIndex:0]);
Sample o/p.
In Original::
object is:abc, at :0x7f8a5a58e750; Address of object pointer is : 0x7fff50cdd750
object is:xyz, at :0x7f8a5a58ff70; Address of object pointer is : 0x7fff50cdd750
object is:(
1,
2,
3,
123
), at :0x7f8a5a591200; Address of object: 0x7fff50cdd750
In Deep::
object is:abc, at :0x7f8a5a58e750; Address of object pointer is : 0x7fff50cdd708
object is:xyz, at :0x7f8a5a58ff70; Address of object pointer is : 0x7fff50cdd708
object is:(
1,
2,
3,
123
), at :0x7f8a5a591200; Address of object pointer: 0x7fff50cdd708
Address of Original : 0x7fff50cdd760
Address IN Original : 0x7f8a5a591230
Address in first object of original : 0x7f8a5a58e750
Im getting the same address for &obj for all the elements in the arrays above. Anything Im missing here? Thanks for your help.
The obj is a pointer which holds the address of another variable. If you change the value of that pointer it won't change it's address. In details,
id obj = original[0];
If you use
NSLog(#"%p",obj);
It'll print the address of the object contained in original[0]. And if you use
NSLog(#"%p",&obj);
It'll print the address of obj.
So even if you change the value like:
obj = original[1];
NSLog(#"%p",&obj);
Will give you same pointer address (Address of obj is not changing only the value of obj is changing)
-[NSArray mutableCopy] doesn't do a deep copy. Even if it did, those are constant strings you're trying to copy. NSString is immutable, so actually making a copy would be a waste of time and memory.
If you want to do a deep copy on an array, you need to do something like this:
NSMutableArray *copiedArray = [NSMutableArray new];
for (id obj in originalArray) {
[copiedArray addObject:[obj copy]];
}
Of course, this only works if all of the objects in your array support NSCopying.
You could get clever and make a category on NSArray that does something similar. You should check, though, that all of your objects conform to NSCopying.
I have a generic person object with properties personName, lastName, and age. I am storing the user input into an NSMutableArray and I wanted to find a under by his/her name in the array. I have tried finding a bunch of different solutions but none that quite really work.
This is my main.m
#autoreleasepool {
char answer;
char locatePerson[40];
//Create mutable array to add users for retrieval later
NSMutableArray *people = [[NSMutableArray alloc] init];
do{
Person *newPerson = [[Person alloc]init];
[newPerson enterInfo];
[newPerson printInfo];
[people addObject:newPerson];
NSLog(#"Would you like to enter another name?");
scanf("\n%c", &answer);
}while (answer == 'y');
NSLog(#"Are you looking for a specific person?");
scanf("%c", locatePerson);
//This is where I need help
int idx = [people indexOfObject:]
}
This is very basic but I am new to objective-c and I wanted to try and find the user by name. The solutions I've seen have used the indexesOfObjectsPassingTest method. But I was wondering if I can't just use the indexOfObjectmethod the way I did there to locate a person by its name?
Any help is appreciated.
This is one of those hard problems you should avoid with some up-front design. If you know that you are putting things into a collection class and will need to get them out again based on some attribute (rather than by order of insertion) a dictionary is the most efficient collection class.
You can use a NSDictionary keyed with Person's name attribute. You can still iterate over all the objects but you will avoid having to search the whole collection. It can take a surprisingly long time to find a matching attribute in a NSArray! You wouldn't even have to change your Person object, just do
NSDictionary *peopleDictionary = #{ person1.name : person1, person2.name : person2 };
or add them one by one as they are created into a NSMutableArray.
You can try something like this assuming that 'name' is a property for your Person class.
NSUInteger i = 0;
for(Person *person in people) {
if([person.name isEqualToString:locatePerson]) {
break;
}
i++;
}
I have an NSMutableArray that contains objects of type Person. The Person object contains parameters of NSString *name, NSString *dateStamp, and NSString *testScore. What I would like to do using fast enumeration, is to check to see in the NSMutableArray *testResults, is see if an object with the same name parameter exists.
If it does, then I want to replace the existing object in the NSMutableArray, with the object that I am about to insert which will have the most current dateStamp, and testScore values. If an object with no matching name parameter is found, then simply insert the object that I have.
My code so far looks like this:
This is the code that creates my object that I am about to insert:
Person *newPerson = [[Person alloc] init];
[newPerson setPersonName:newName]; //variables newName, pass, and newDate have already been
[newPerson setScore:pass]; //created and initialized
[newPerson setDateStamp:newDate];
and here is the code where I try to iterate through the NSMutableArray to see if an object with the same name parameter already exists:
for (Person *checkPerson in personList) { //personList is of type NSMutableArray
if (newPerson.newName == checkPerson.name) {
//here is where I need to insert the code that replaces checkPerson with newPerson after a match has been found
}
else {
personList.addObject(newPerson); //this is the code that adds the new object to the NSMutableArray when no match was found.
}
}
It's not a very complicated problem, but I am confused as to how to go about finding a match, and then replacing the actual object without knowing ahead of time what index the object resides in.
You want to use indexOfObjectPassingTest to look for a match:
NSInteger indx = [personList indexOfObjectPassingTest:^BOOL(Person *obj, NSUInteger idx, BOOL *stop) {
return [obj.name isEqualToString:newPerson.name];
}];
if (indx != NSNotFound) {
[personList replaceObjectAtIndex:indx withObject:newPerson];
}else{
[personList addObject:newPerson];
}
Notice that I used isEqualToString: to compare the two strings not ==. That mistake has been asked about and answered a million times on this forum.
You have some inconsistency in your naming. In the question, you say the Person objects have a name property, but when you create a new person you use setPersonName, which would imply that the property name is personName. I assumed, just name in my answer.
I have a webservice that returns data to my client application in JSON. I am using TouchJson to then deserialize this data into a NSDictionary. Great. The dictionary contains a key, "results" and results contains an NSArray of objects.
These objects look like this when printed to log i.e
NSLog(#"Results Contents: %#",[resultsArray objectAtIndex:0 ]);
Outputs:
Results Contents: {
creationdate = "2011-06-29 22:03:24";
id = 1;
notes = "This is a test item";
title = "Test Item";
"users_id" = 1;
}
I can't determine what type this object is. How do I get the properties and values from this object?
Thanks!
To get the content of a NSDictionary you have to supply the key for the value that you want to retrieve. I.e:
NSString *notes = [[resultsArray objectAtIndex:0] valueForKey:#"notes"];
To test if object is an instance of class a, use one of these:
[yourObject isKindOfClass:[a class]]
[yourObject isMemberOfClass:[a class]]
To get object's class name you can use one of these:
const char* className = class_getName([yourObject class]);
NSString *className = NSStringFromClass([yourObject class]);
For an NSDictionary, you can use -allKeys to return an NSArray of dictionary keys. This will also let you know how many there are (by taking the count of the array). Once you know the type, you can call
[[resultsArray objectAtIndex:0] objectForKey:keyString];
where keyString is one of #"creationdate", #"notes", etc. However, if the class is not a subclass of NSObject, then instead use:
[[resultsArray objectAtIndex:0] valueForKey:keyString];
for example, you probably need to do this for keystring equal to #"id".