Question

I have the next code:

// UITextField+Navigation.h
@interface UITextField (Navigation)

@property (weak, nonatomic) UIControl *nextUIControl;

@end

//UITextField+Navigation.m
@implementation UITextField (Navigation)

- (UIControl *) nextUIControl {
    return objc_getAssociatedObject(self, &defaultHashKey);
}

- (void) setNextUIControl:(UIControl *)nextUIControl {
    objc_setAssociatedObject(self, &defaultHashKey, nextUIControl, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

@end

What's the difference between:

return objc_getAssociatedObject(self, &defaultHashKey);

and

return self.nextUIControl;

I tried both ways, and the second one enter in a infinity loop... why?? maybe it's a obvious answer but I'm a beginner developer ^^'

Thanks in advance.

Was it helpful?

Solution 2

Firstly, you must know than when you write

self.nextUIControl

it actually is compiled in

'return [self nextUIControl]'

The dotSyntax in objective-C is not to access the local variable like in java but to provide a more readable syntax to call the getters and setters.

So, in a getter for the property variable, you should not return self.variable, cause that would be an infinite loop.

If you want to return the local variable, you can't write _nextUIControl (this is your private local variable automatically generated by the property). However, here in this scenario, you are in a objective-C categorie, and, because of the 'protected' visibility doesn't exist in objective-C, the category cannot access directly _nextUIControl, so one has to use the syntaxe objc-get / objc-set to get and set the value for the object at the address &defaulthashkey.

OTHER TIPS

self.nextUIControl is the dot notation for [self nextUIControl]. So what happens, in fact, is you are calling an endless recursion.

Your code demonstrates a property defined in a class category. Since categories cannot introduce additional instance variables, associated objects are used for both setting and getting.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top