I intend to call default init method in init method with arguments, in iOS. like this:
-(id)init{
self = [super init];
if (self) {
Office = [[NSString alloc]init];
}
return self;
}
-(id)initWithOffice:(NSString*)office{
self = [self init];
if (self) {
self.Office = itemDescription;
}
return self;
}
My question is it a good practice, What should be done?
I appreciate your response in advance,
That will work, but I would prefer the following as it doesn't allocate an empty string, only to be replaced with the initializing string:
-(id)initWithOffice:(NSString*)office{
self = [super init]; // Not [self init]
if (self) {
Office = office; // OK if using ARC
}
return self;
}
The first init method doesn't make a great deal of sense; I think simply leaving Office as nil is better (NSString objects are immutable). As pointed out by #H2CO3, the initWithOffice method becomes the designated initializer for the class and all other init methods should use it to initialize the object. With that in mind the first init method should be:
-(id)init{
return [self initWithOffice:nil];
}
Creating a method starts with initWith is to see what values will be passed. It helps you to remind which values should be sent and allocated in the method. Consider you have 4 variables to init when the view is initialized. It's best to keep a separate initWith method where you can init your view and other variables you customize.
I think you should improve you object assignning logic,Like that...
-(id)initWithOffice:(NSString*)office{
self = [self init];
if (self) {
self.Office = [[NSString alloc] initWithString:office]; //Purpose is that //the office object can only be released by the self, non other classes (The owner //of the variable should be self).
}
return self;
}
Related
I have seen self = [super init] in init methods. I don't understand why. Wouldn't [super init] return the superclass? And if we point self = [super init], are we not getting self = superclass?
Here's an example code fragment
- (id)init
{
if (self = [super init]) {
creationDate = [[NSDate alloc] init];
}
return self;
}
Hope someone can clarify this for me. Thank you.
Assuming that MyClass is a subclass of BaseClass, the following happens when
you call
MyClass *mc = [[MyClass alloc] init];
[MyClass alloc] allocates an instance of MyClass.
The init message is sent to this instance to complete the initialization process.
In that method, self (which is a hidden argument to all Objective-C methods) is
the allocated instance from step 1.
[super init] calls the superclass implementation of init with the same (hidden)
self argument.
(This might be the point that you understood wrongly.)
In the init method of BaseClass, self is still the same instance of MyClass.
This superclass init method can now either
Do the base initialization of self and return self, or
Discard self and allocate/initialize and return a different object.
Back in the init method of MyClass: self = [super init] is now either
The MyClass object that was allocated in step 1, or
Something different. (That's why one should check and use this return value.)
The initialization is completed (using the self returned by the superclass init).
So, if I understood your question correctly, the main point is that
[super init]
calls the superclass implementation of init with the self argument,
which is a MyClass object, not a BaseClass object.
As you have Question self = [super init] in the if Condition suggest a specific meaning.
First of all [super init] gives the initialization of the superclass of the existing class which is in use currently. Using [super init] gives the super class initialization which shows that object exist of the class.
Now when you use self = [super init] that means you are assigning the class to the self for the further utilization of the same class.
And at the end you put it in if condition as if(self = [super init]) this means you are checking whether the object of the class exist of not to prevent the foul behavior of the application.
I think it is clear now!!!
#MartinR has a very good answer. But do you ever wonder why "[super init] calls the superclass implementation of init with the same (hidden) self argument. (This might be the point that you understood wrongly.)" works in his 3rd point ?
Here is the excerpt from Big Nerd Ranch guide 3rd edition, chapter 2 Objective C that clarifies this point
“How does super work? Usually when you send a message to an object,
the search for a method of that name starts in the object’s class. If
there is no such method, the search continues in the superclass of the
object. The search will continue up the inheritance hierarchy until a
suitable method is found. (If it gets to the top of the hierarchy and
no method is found, an exception is thrown.)”
“When you send a message to super, you are sending a message to self,
but the search for the method skips the object’s class and starts at
the superclass.”
This code shows how iOS Runtime performs this task
objc_msgSendSuper(self, #selector(init));
Every method that you declare has two hidden parameters: self and _cmd.
The following method:
- (id)initWithString:(NSString *)aString;
is converted by the compiler to the following function call:
id initWithString(id self, SEL _cmd, NSString *aString);
see this link for more:
http://www.cocoawithlove.com/2009/04/what-does-it-mean-when-you-assign-super.html
Self = [super init];
According to JAVA, this mean a pointer to instance itself so object can message itself.
Same meainng of Self here in objective C,
According to JAVA, Super mean that allow to access base or parent class
Same meainng of Super here in objective C,
Now init instance to to complete the initialization process.
I would think of it as, init'ing all the supers variables etc, then you get to init your extended classes variables before it is returned.
[super init] is the same as [self superclass_variant_of_init]
If you want to send a message to superclass, there is another approach (without using runtime library):
[[self superclass] init];
From Apple's Documentation:
Because an init... method might return nil or an object other than the one explicitly allocated, it is dangerous to use the instance returned by alloc or allocWithZone: instead of the one returned by the initializer. Consider the following code:
id myObject = [MyClass alloc];
[myObject init];
[myObject doSomething];
The init method in the example above could have returned nil or could have substituted a different object. Because you can send a message to nil without raising an exception, nothing would happen in the former case except (perhaps) a debugging headache. But you should always rely on the initialized instance instead of the “raw” just-allocated one. Therefore, you should nest the allocation message inside the initialization message and test the object returned from the initializer before proceeding.
id myObject = [[MyClass alloc] init];
if ( myObject ) {
[myObject doSomething];
} else {
// error recovery...
}
I've been creating custom initializers for my objects just because it feels like better practice than setting their variables in other ways. In these initializers I usually set the variables of the object then return a call to the main init.
So, for example, in a UIViewController subclass my code would look something like this:
-(id)initWithValue:(int)val {
self.value = val;
return [self initWithNibName:nil bundle:nil];
}
where value is an integer that belongs to that ViewController subclass, and there are usually more values than that.
However, recently I started setting self first because I thought that the self = [self init...] would replace the current instance of the class and thus I would lose that instance of self.
So, I have started doing:
-(id)initWithValue:(int)val {
self = [self initWithNibName:nil bundle:nil];
self.value = val;
return self;
}
I then recently checked the original version and realized that everything does work properly and the change was unneccessary.
So, my question is this:
What does the [super initWithNibName:bundle:] do which is causing it to create an object but not replace the original object?
Is one of the two versions better than the other to use or are they both equivalent? If one is better, which should be used?
Thanks in advanced!
You should do it the following way:
- (id)initWithValue:(int)val {
self = [super initWithNibName:nil bundle:nil];
if (self) {
_value = val;
}
return self;
}
In iOS, a common pattern is to return nil if the parameters sent to init methods are invalid. The value will be one of 2 things: the current pointer to self or nil. If the call to super returns nil then the object was not setup properly so you should also return nil. Doing self = [super initWithNibName:nil bundle:nil]; just makes it easier to respect the possible nil value returned by super
Please use the following code to override init method
-(id)initWithValue:(int)val
{
self = [super init];
if(self)
{
self.value = val;
}
return self;
}
The first code which you have written won't store the value, because before creation of the object you are trying to store data.
But, the second code, needed a small modification for better practice i.e, like this...
-(id)initWithValue:(int)val {
self = [self initWithNibName:nil bundle:nil];
if(self)
_value = val;
return self;
}
Hope this is useful to you...:-)
the [super initWithNibName:bundle:] actually invoke the method of the superclass.
if you use [self initWithNibName:bundle:] actually it will call the rewriting of initWithNibName:bundle: of course you must have rewrote it,otherwise it will also call the superclass method. so if you want to do some initialize in the rewrite of initWithNibName then you can use [self initWithNibName:bundle:] but if you don't need do the extra initialize there is no difference between the to method;
I'm pretty new to Objective-C and I have a question.
I have created a custom class and tried to create overloads for Initialization:
- (id)init
{
if (self = [super init]) {
[self setIsCurrentCar:NO];
}
return self;
}
-(id) initWithID:(NSInteger)id {
if(self = [self init]) {
[self setID:id];
}
return self;
}
-(id) initWithID:(NSInteger)id CarYear:(NSString *)year {
if(self = [self initWithID:id]) {
[self setCarYear:year];
}
return self;
}
Let's say at one point, I call the -(id) initWithIDCarYear method.
I'd like to know the code above is structurally correct.
In this code, self is set for 3 times. Is there a better
solution?
Do I have memory leak in this code? (using ARC)
Do I have to check for if(self = ...) always or it is a
redundant code?
Thank you
#Edit
Is the following code better?
-(id) initWithID:(NSInteger)id CarYear:(NSString *)year {
if (self = [super init]) {
[self setIsCurrentCar:NO];
[self setID:id];
[self setCarYear:year];
}
return self;
}
While your code is ok, i would structure the init-calls in the reverse order, where the most detailed one is the designated initializer and the more general ones would bubble some default values up:
-(id) initWithID:(NSInteger)id
CarYear:(NSString *)year
{
if(self = [super init]) {
_year = year;
_id = id;
}
return self;
}
-(id)initWithID:(NSInteger)id
{
return [self initWithID:id CarYear:#"unset"];
}
-(id)init
{
return [self initWithID:0];
}
if calling one of the more general initializer would generate an illegal state, you could instead throw an error to prohibit using it.
let's assume, a car needs to have a ID, but not a year. It would be ok to use initWithID but using init would lead to an inconsistent state, so we want to force not to use it:
-(id)init
{
[NSException raise:NSInternalInconsistencyException
format:#"You must use -initWithID: or -initWithID:CarYear:", NSStringFromSelector(_cmd)];
return nil;
}
In this code, self is set for 3 times. Is there a better solution?
see above
Do I have memory leak in this code? (using ARC)
No, everything is fine
Do I have to check for if(self = ...) always or it is a redundant code?
As I showed you: you can call different init methods in a chain. just the last in that chain needs to perform that.
-(id) initWithID:(NSInteger)id CarYear:(NSString *)year {
if (self = [super init]) {
[self setIsCurrentCar:NO];
[self setID:id];
[self setCarYear:year];
}
return self;
}
You should not use setters on self in init-methods, see Apple's docs.
I'd like to know the code above is structurally correct.
Yes. I don't see any problem with it.
In this code, self is set for 3 times. Is there a better solution?
That's pretty normal. I wouldn't bother changing that.
Do I have memory leak in this code? (using ARC)
No.
Do I have to check for if (self = ...) always or it is a redundant
code?
You don't have to, but you definitely should. See this question for details.
It looks like you have one mandatory initialized variable and two that are effectively optional.
I'd recommend implementing an init method and two #property()s for the ID and carYear. That reduces the # of initializers and better reflects that usage contract of the class.
From my little knowledge... tried to create overloads for Initialization this statement should not been used here.
As typically overload means same name multiple arguments, but in obj-c we do not follow this. In obj-c overloading is faked by naming the parameters.
So here you have 3 different sets of code, and each one is called some other method. And you do not have a memory leak as you are not allocating memory thrice for same object, instead you are initializing it.
I have a uitextfield subclass and in the init method and setDelegate I have this:
- (void) setDelegate:(id<UITextFieldDelegate>)paramDelegate{
[super setDelegate:paramDelegate];
MRAAdvancedTextFieldDelegate *limitedDelegate = [[MRAAdvancedTextFieldDelegate alloc] init];
self.delegate = limitedDelegate;
}
I am using ARC, but this results in a BAD_ACCESS. Any ideas?
You write self.delegate = limitedDelgate within your setDelegate: method. This is exactly the same as calling [self setDelegate:limiatedDelegate]. Since you are within the -setDelegate: method itself, you are causing infitine recursion. Hope this helps!
EDIT: per your comment about your intention, override it like this:
- (void) setDelegate:(id<UITextFieldDelegate>)paramDelegate{
MRAAdvancedTextFieldDelegate *limitedDelegate = [[MRAAdvancedTextFieldDelegate alloc] init];
[super setDelegate:limitedDelegate];
}
But I don't believe it's a good idea to do this - you should have your client code pass in instances of your delegate instead.
self.delegate = limitedDelegate;
is turned into
[self setDelegate:limitedDelegate];
by the compiler, resulting in an infinite loop. Solution: instead of using the property, use the instance variable instead in the custom setter method:
delegate = limitedDelegate;
originally, I have a default init function
-(id) init
{
if (self=[super init])
{
......
}
return self;
}
However, I like to override the init function to pass in custom objects or other objects
like
-(id) initWithScore:(NSString*) score
{
if (self=[super init])
Now there is an error saying [super init] function can only be called with -(id) init function.
So what do I do to fix it so I can pass in objects and also use self=[super init]?
Error:Cannot assign to self outside of a method in the init family.
I was trying to convert a projet to ARC and after creating a new one and including the files from the old one - one of the issues i got was
Cannot assign to 'self' outside of a method in the init family
The selector name MUST begin with init - not only that in my case the init selector was:
-(id)initwithPage:(unsigned)pageNum {...}
Notice the small 'w'.
I have changed it to:
-(id)initWithPage:(unsigned)pageNum {...}
Notice the capital 'W'!
My problem was solved.
I hope this helps someone.
You need to return an object of type id in your new method.
Suppose you have declare an NSString *myscore property, you will write something like this:
-(id) initWithScore:(NSString*) score
{
self=[super init];
if (self)
{
self.myscore = score;
}
return self;
}