How do I write my own "extension method" in objective-c?
http://code.google.com/p/json-framework/
This library does it and it works like this.
NSString *myString = ...;
id myResult = [myString JSONValue];
where the myResult
returns an NSDictionary
or NSArray
.
What are these called? How do I write my own?
An extension is adding private methods and private variables that are only specific to the class. Any method or variable declared inside the extensions is not accessible even to the inherited classes.
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are static methods, but they're called as if they were instance methods on the extended type.
Difference is that one is for using Swift code in ObjC and the other one is for using ObjC code in Swift.
In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type.
This is done by the use of categories. You can use categories to add methods to any class. See: https://developer.apple.com/library/mac/documentation/cocoa/conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html#//apple_ref/doc/uid/TP40011210-CH6-SW1
Example:
#import "ClassName.h"
@interface ClassName ( CategoryName )
// method declarations
@end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With