objective-c query

iconara

Registered
Code:
- (void) setName: (NSString *)newName {

	[name release];

	name = [newName retain];

}

ok, that's just fine, but what if i want to name my argument "name" instead of "newName". please rewrite the method if the first line looks like this:

Code:
- (void) setName: (NSString *)name


what I want to do is, written in java:

Code:
void setName(String name) {
	this.name = name;
}
there seems to be no equivalent of "this" in objective-c, and if there were how would one use it? there is "self", but it's not the same as "this", in the java sense.

[self name] = [name retain]; won't work that well...


theo
 
Forgive me if I am misunderstanding your question, but perhaps you may need to rewrite your setName method. Instead of returning (void) you may want to try:

- (id) setName: (NSString*) name;

You see, the call to [name retain] returns a type of (id), which you have released in the call to [name release]. The compiler should generate a warning here.

HTH! regards
 
1) Yes you misunderstood

2) No, the code compiles fine. A return-type of void is no problem if I don't return anything. Had I set the return type to id and still not explicitly returned something, self would be returned.

3) Tanks anyway =)


The question is this: how can I have an argument with the same name as an instance variable, and still assign to that variable.

It could problably be done like this:

Code:
- (void)setName:(NSString *)name {
    [[self name] release]
    self->name = [name retain];
}

since everything is a struct anyway (I think), but this code is so ugly that I'm ashamed that I have event written it down...



theo
 
You can simply do:
Code:
- (void) setName: (NSString *)newName
{
	[name autorelease];
	name = [newName copy];

}

That's how I do it at least ;)
 
well, I realize that (it was in my first post...), but I don't want to... it's ugly (in my opinion), it would be nicer to be able to do it in a similar fashion to java

regards
theo
 
The struct pointer thing is probably the way to go I'm afraid. I found a similar use of it in <i>"Object Oriented Programming and the Objective-C Language"</i> on page 74. Sometimes Obj-C is too close to plain old C for my taste. :(
 
Back
Top