Calling a public method - iphone

I'm trying to figure out how to centralize a method that I use in a few of my ViewControllers. I already had a singleton that I was using for some variables. I called the singleton class Shared.
I moved my method to the Shared class and tried calling it like so:
m.createdAt = [Shared getUTCFormateDate:[messageObject objectForKey:#"created_at"]];
It's giving me an exception saying that the selector doesn't exist when it tries to call it.
I have already imported Shared.h. Any other thoughts would be appreciated.

If your class is named "Shared" then it looks like you are trying to call a class method rather than an instance method. So, you need to declare the method with + instead of -.

here is the correct pattern for creating a Singleton in objective-c: (Ill use an example of a User object.. taken from code I have open in front of me). also, please note that there is a difference between Singleton classes and Static Class methods, as discussed here.. Difference between static class and singleton pattern?
in the .h file, declare a static method that returns an instance of your class.
+(User *) currentUser;
in the .m file, create a static variable that holds your instance
static User * _user;
then, in your .m class, create your "public" static accesor GET that returns or instantiates and returns your static variable
+ (User *) currentUser
{
if (!_user)
{
_user =[[User alloc]init];
// ... init the singleton user properties and what not
// ...
}
return _user;
}
then, when you want to call on your Singleton class you just make sure that User.h is imported and call [[User currentUser] someMethodorProperty];
enjoy

Related

turn away to assign a property from Class method

I am just curious as if there is anyway to assign a property that is being triggered from class method?
Ex:
+ (void)asyncResponse:(NSDictionary*)response:(NSError*)error
I am getting a response of NSURLConnection in that call, however, I am trying to use this in my another class and set that dictionary as a property, but it gives me the error as this is a class method. That asyncResponse is a "Delegate call" I am using to direct to any particular class in runtime.
Thanks.
There are lot of options you may use to store the variable. Why do you need a property in class method. Class method is run when there is no role of instance. But, of course you, could pass create an instance of the class in the class method and store the value in the object. Other way would be to create some global variables and assign the values to it such that it can be accessed through out the class.
Creating instance to store the variable into property;
+ (void)asyncResponse:(NSDictionary*)response:(NSError*)error{
MyClass *me = [[MyClass alloc] init];
me.someProperty = response;
}
But, I dont think you were looking for this, because it is very simple use of the class and properties.
The other thing you could do is create some static variables inside your implementation and then access those variables through your class. You could even create your own custom getter and setter for it, for more easy uses.
#interface MyClass:NSObject
+(void)setResponse:(NSDictionary*)response;
+(NSDictionary*)response;
#end
NSDictionary *globalResponse;
#implementation MyClass
+(void)setResponse:(NSDictionary*)response{
if(response != globalResponse){
globalResponse = response;
}
}
+(NSDictionary*)response{
return globalResponse;
}
You could set the default value for the response in initialize or load method. This makes a simple class level property.

Adding custom behavior and state to all my classes

I want to add functionality and another property to ALL of my classes.
So I wrote a category:
#implementation NSObject (MyCategory)
And I declared a static property in it:
static MyObj myObj;
And I created 2 class methods to get and set it:
+ (MyObj) getMyObj {
return myObj;
}
+ (void) setMyObj:(MyObj)obj {
myObj = obj;
}
Now I imported NSObject+MyCategory.h in my .pch file, so all classes will be effected by this. Indeed all classes now have the new functionality and state:
#import "NSObject+MyCategory.h"
The problem is that when I set myObj, it changes myObj on all classes. All classes share 1 myObj.
I want each class to have its own myObj that is added using the category. I don't want one myObj, rather I want as many myObj's as classes. Each class should have its own myObj.
Thanks,
Nur
You can not add properties instance variables to a class in categories. Either subclass NSObject or use associated objects.
Your solution adds a single static variable (not "property", in Objective-C that means something else), there is no way using categories to add a static variable per class.
However your idea is close to what will work for you; if you can only have one variable and want to store many values what can you use? A dictionary.
static NSMutableDictionary *References;
+ (void) load
{
// load is called exactly once when this category is first loaded,
// setup the dictionary
References = [NSMutableDictionary new];
}
+ (void) setMyObj:(MyObj)reference
{
// NSMutableDictionary will take any object reference as a key,
// for a class method self is a reference to the unique class object,
// so use self as the key and store the reference
[References setObject:reference forKey:self];
}
+ (MyObj) getMyObj
{
// returns previously stored reference or nil if there isn't one for this class
return [References objectForKey:self];
}
HTH

how to getItmes from sqlite data base calling the method in any other class instead of appDelegate in iphone

I have getQuestions method in QuestionData like the following signature i want that
user may call this function in other class except appDelagate how to call this there becuase getDBPath is declared in appDelegate..
how to access this method in any other class
[QuestionData getQuestions:[self getDBPath]];
+ (void)getQuestions:(NSString*)dbPath{

Objective-C Runtime: How to remove a method from a class?

In the Objective-C Runtime Reference, I see class_addMethod but not class_removeMethod. How do I dynamically remove a method?
Also, does class_addMethod add an instance method or a class method?
As Inerdial mentioned in his comment, the main question (How can a method be removed from a class at runtime?) is somewhat exhaustively answered here.
MattDiPasquale asks as well:
Also, does class_addMethod add an instance method or a class method?
Inerdial is correct again:
class_addMethod adds an instance method, and that to add a class method, you need to add an instance method to the class' class.
Given a Class c, we can get our hands on the class of which it is an instance (known as its "metaclass") as simply as
Class metac = object_getClass(c);
To then "add a class method" to c, we add a method to metac using class_addMethod.
If, for example, elsewhere we have already defined
id myClassMethodImplementation(id self, SEL _cmd) {
//implementation
}
We can then add a class method to c as follows:
BOOL success = class_addMethod(metac, #selector(myClassMethod), (IMP)myClassMethodImplementation, "##:");
or equivalently
BOOL success = class_addMethod(object_getClass(c), #selector(myClassMethod), (IMP)myClassMethodImplementation, "##:");
To simply add this same method as an instance method on c, we simply write
BOOL success = class_addMethod(c, #selector(myClassMethod), (IMP)myClassMethodImplementation, "##:");
References:
1. Objective-C Runtime Reference 2. Objective-C Runtime Programming Guide - Type Encodings 3. Cocoa with Love - What is a meta-class in Objective-C?

In Objective-C, when should I use class methods and when should I use instance methods?

What is the difference between class and instance methods in Objective-C and when should I use each of them?
Using the tired old Car analogy...
Think of a Class like it is a factory that makes Instances of the class. For example, you might have a Car class and you might declare a method like:
+ carWithColor: (NSColor *) aColor;
And that method would then create a new Car instance, set the color, and return it:
+ carWithColor: (NSColor *) aColor
{
Car *aCar = [[[self alloc] init] autorelease];
[aCar paintWithColor: aColor];
return aCar;
}
Now, that Car class would then declare an instance method that allows the car to be painted. Why an instance method? Because every car can have a different color (and the color of the car would likely be stored in an instance variable).
- (void) paintWithColor: (NSColor *) aColor
{
... do your paint stuff here ...
}
This is explained in the Objects, Classes, and Messaging section of the Objective-C documentation.
This is an old post, but since it comes up first in a Google search I thought I'd add to it.
I'm not going to talk about class methods used as factory methods. I'd like to talk about their use in utility methods. You can/should use class methods for utility methods that are independent of state. What does this mean? Well, for instance, if you're formatting a date the same way for all instances, that's a utility method that should be a class method. Think of the utility method like a screw driver. You don't need to make a new instance of the screw driver every time you want to do something with it. The screw driver remains constant. So, for instance, I have a class that includes a private method that generates a string of emDashes used for displaying to the view. This method is not dependent on state and hence will not vary by instance. Think of class utility methods like constants.
+ (NSString *)emDashString {
return #" \u2014 \u2014 \u2014 \u2014 \u2014 \u2014 \u2014 \u2014 \u2014";
}
You can call this method generically within the class (it's private in my example) like this:
NSString *string = [[self class] emDashString ];
I've deliberately chosen a bit of a trivial example to drive the point home. You would only bother making this a class utility method if you're going to need this string more than once in your class. Notice that instead of referring to the class by name I call it generically with [self class] since this is called internally. If it's exposed and you want to call it from another class then refer to it by the class name as usual.
Instance methods do things with instances of a class:
NSString *myString;
myString = [[[NSString alloc] initWithString:#"Hello, world."] autorelease];
NSLog (#"myString's length: %u", [myString length]); // instance method
Class methods can do class-specific things without relying on an object instance, often returning an instance of the class, or some other class-specific result:
NSLog (#"%#", [NSString stringWithString:#"Hello, world."]); // class method
I think it may be rare to see class methods that do not return something.
You don't need to implement both. Either option is available to you as you design your class.
An instance method can operate on an instance of the class. This can get or set a property, or cause behavior you only want that instance to perform. You need to actually have an instance to use it. These can either use or change the state of the instance.
// Notional instance methods
myHouse.color = blueColor;
[myCar accelerate];
speed = myCar.speed;
A class method operates on the notion that the class exists. It can be used to create an instance, or perform a calculation that doesn't depend on having an instance. You might have a class for custom math helper, that essentially contains functions.
// Notional class method uses
myString = [NSString stringWithFormat:#"&f", floatToConvert];
myResult = [MyMathHelper MyFunctionWithInput:myInput];
Class method signatures are prefixed with +, instance methods with - so in your header file declarations would look something like this:
-(void)setAllThings:(NSArray*)things; //instance method
+(void)setAllClassThings:(NSArray*)things; //class method
And of course the same rules apply when you define the methods in the .m file.