Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How to define public methods?

How can I define a method that can be called from anywhere, in every viewcontroller class?

I have a method that brings me a json file, and i want it to be reusable, since i have several json calls on my app.

Can you help me?

like image 678
88fsantos Avatar asked Jun 01 '12 15:06

88fsantos


People also ask

How do you make a method public in Objective-C?

A property is saved in an object, so you can create an object ITYourCustomClass *objectOfYourCustomClass = [[ITYourCustomClass alloc] init]; and setting the properties objectOfYourCustomClass. title = @"something" . Then you can call [objectOfYourCustomClass doSomethingWithTheTitle]; , which is a public object method.

How do you define a class in Objective-C?

In Objective-C, classes are defined in two parts: An interface that declares the methods and properties of the class and names its superclass. An implementation that actually defines the class (contains the code that implements its methods)


1 Answers

You can add it through a category:

EDIT

Create a new .h .m file pair and in the .h file:

@interface UIViewController(JSON)
-(void) bringJSON;
-(void) fetchData:(NSData*) data;


@ end

Then in the .m file:

@implementation UIViewController(JSON)

-(void) bringJSON {

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

[NSData dataWithContentsOfURL:yourURL];

[self performSelectorOnMainThread:@selector(fetchData:)
withObject:data waitUntilDone:YES];

});

}


-(void) fetchData:(NSData*) data {

//parse - update etc.

}


@end

Where I'm just assuming that you'll be returning an NSArray, you can put any method there and extend all UIViewControllers. The method bringJSON will be available to all UIViewControllers and its subclasses.

like image 170
Kaan Dedeoglu Avatar answered Nov 09 '22 23:11

Kaan Dedeoglu