I'm not new to coding, but just getting back into it. I learned Java in school, but I'm starting to learn Objective C. Basically, forgive how remedial this question is. I couldn't find anything this simple by searching, which is why I ask.
Anyways, I have below the code for my officeLife.m file. My two main classes that I'm working with are Person.h/.m and officeLife.h/.m. I tried to define the Person class by simply adding variables like name and age to the object, and wanted to use officeLife to create and add specific Person objects to an array called employees. The problem is when I go to set the name for the Person in officeLife.m (displayed below) I'm not sure how to access the setters/getters that were synthesized for me in Person.m. I know it would look like: [nameOfPerson firstName: Sam]
if I were in the Person class making the call, but what would this look like in a different class/file?
#import "officeLife.h"
#import "Person.m"
@implementation officeLife
@synthesize employees;
- (Person*) hirePerson:(NSString *)name andLastName:(NSString*)name2
{
if([employees count] == 0)
开发者_高级运维 {
employees = [[NSMutableArray alloc] init ];
}
else
{
Person *name = [[Person alloc] init];
name.firstName =
}
Before I answer your question, I'm going to offer a brief summary of a few Objective-C conventions:
Class names are Capitalized. Variable names are camelCased. Setter methods take the form -[setFoo:] Getter methods take the form -[foo]
Person *p = [[Person alloc] init];
[p setFirstName:@"Jimi"];
// or - p.firstName = @"Jimi"
// BOTH invoke the same setter method (somewhat unintuitive)
That's my best guess; I don't have your Person interface in front of me (please post it). Considering you are new to Objective-C, I recommend that you avoid the @synthesize directive temporarily and write your own setter/getter methods. You'll get a better feel for the language, but you'll also be exposed to retain/copy/release strategies and potential issues with memory references (it's important that you know what you're up against ;))
As an example:
@interface Person : NSObject {
NSString *firstName;
}
- (void)setFirstName:(NSString *)s {
if (s != firstName) { // this compares memory references, _not_ string content
[firstName release];
firstName = [s retain];
}
}
- (NSString *)firstName {
return firstName;
}
In the setter method, the condition is important because if for some reason, both the ivar and parameter refer to the same memory location, releasing the ivar would release the parameter as well, causing a host of problems.
Also, in your code, in the else {} block, you declared a variable 'name' which "clashes" with the parameter 'name'. While this is legal, any references to 'name' in the else {} block refer to the local variable, not the parameter. You may want to change the name of one of the variables.
精彩评论