3

for example:

in interface:

@property(retain) NSObject* anObject;

in interface, in implemetation:

-(id)initWithAnotherObject:(NSObject*)another{
    if(self = [super init]){
         anObject = another;    //should this be anObject = [another retain]?
    }
    return self;
}
2
  • Where you have NSObject in your code examples, you really need NSObject*. Objective-C objects are always passed by reference, but unlike Java, you must explicitly tell the compiler by using pointers to NSObject.
    – JeremyP
    Apr 28, 2011 at 8:54
  • oh, this is a typo, thank you.
    – CarmeloS
    Apr 28, 2011 at 10:16

2 Answers 2

6

Yes, as you cannot guarantee that 'another' lifetime will be the same as lifetime of the object you create you need to ensure that by retaining it in init method (and do not forget to release it in dealloc method). So the following is correct:

...
if(self = [super init]){
     anObject = [another retain];
}
...

One more thing - by defining retaining property for anObject you say that you take an ownership of that object and thus you must release it in dealloc method. If you don't retain 'another' parameter in init method it will be eventually released (either in dealloc or in setter method) without being retained - so your application may crash with EXEC_BAD_ACCESS error.

2

I think it's a good practice to do

self.anObject = another;

but it's the same

1
  • It is not the same, by using self you are invoking the setter which could be synthetized as retain. Aug 2, 2011 at 20:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.