Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Extension Methods" in Objective-C

Tags:

objective-c

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?

like image 950
Daniel A. White Avatar asked Jan 29 '10 00:01

Daniel A. White


People also ask

What are extensions in Objective-C?

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.

What is meant by extension method?

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.

What are the file extensions of Objective-C and swift?

Difference is that one is for using Swift code in ObjC and the other one is for using ObjC code in Swift.

When to use extension methods in c#?

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.


1 Answers

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
like image 195
Chris Farber Avatar answered Sep 20 '22 08:09

Chris Farber