Custom UITextField delegate - ios

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;

Related

Not going into method

I'm just learning iOS development but I have experience in C++ and I'm having an issue where my I call a method on an object but that object is not being called. Here is my code:
#implementation EXCoursesViewController{
EXNetworkingController *_networkController;
}
-(instancetype)initWithStyle: (UITableViewStyle)style{
self = [super initWithStyle: style];
if(self){
self.navigationItem.title = #"Title";
[_networkController createSession];
[self fetchFeed];
}
return self;
}
[_networkController createSession] doesn't seem to actually call the createSession method in the EXNetowrkingController I made. I'm not sure why this is happening. Any help would be greatly appreciated.
I'm not sure why this is happening.
Most likely, it's because _networkController is nil. It's apparently an instance variable, but you haven't given it a value at the point in -initWithStyle: where you're trying to send it a message.
To fix the problem, just create an EXNetworkingController instance and assign it to your ivar before using:
_networkController = [[EXNetworkingController alloc] init]; // or use the correct initializer
[_networkController createSession];
You are not doing the alloc and init for your EXNetworkingController. What i recommend is make your createSession method as public and call it. It can be called through the EXNetworkingController class name itself.
Do something like this:
+(void)createSession{
//Your createSession code goes here
}
You just have to replace the minus(-) which is in front of the -(void)createSession method with plus(+)
Then in your EXCoursesViewController class inside the initWithStyle replace [_networkController createSession]; with [EXCoursesViewController createSession];
And you no longer require to make an object of your EXCoursesViewController.
So you can remove EXNetworkingController *_networkController;
Hope this helps. Thanks.

Objective-c: Questions about self = [super init]

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 intend to call default init method in init method with arguments

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;
}

Custom Object Initializers

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;

Is there a init method in iOS that is always called?

Is there a method that is always called in Cocoa? Many classes have init or initWith, but even worse they can be loaded from a nib or something. I don't want to have to scrape around and find how it does this in this case. I just want to set some initial variables and other things, and I want a method to subclass that I can depend on no matter if it's a UIView, UIViewController or UITableViewCell etc.
No there is not such a method. init comes from NSObject so every object can use it, and as well subclasses define their own initialization methods. UIView, for example, defines initWithFrame: and furthermore there are init methods from protocols, such as NSCoding which defines initWithCoder:. This is the dynamic nature of objective-C, anything can be extended at any time. That being said, there are some patterns. UIViewController almost always takes initWithNibName:bundle: and UIView almost always takes initWithFrame: or initWithCoder:. What I do is make an internal initialize method, and just have the other inits call it.
- (void)initialize
{
//Do stuff
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
[self initialize];
}
}
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if(self)
{
[self initialize];
}
}
Not 100% sure that it is always called, but I am pretty sure that this is a viable option. To be perfectly honest, I can't recall that I have ever seen this method used in practice and I usually shy away from using this method (I have absolutely no idea why, probably because it's just not the cleanest and most comprehensive method to achieve this...):
-didMoveToSuperview()
From documentation:
Tells the view that its superview changed.
The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever the superview changes.
There's many ways you can write a custom initializer.
- (id)initWithString:(NSString *)string {
if((self == [super init])) {
self.string = string;
}
return self;
}
That's just how I write my initializers in general. For example, the one above takes a string. (you don't have to pass strings if you don't want).
Btw, init is a method. According to the header for NSObject, init has a method implementation.

Resources