I see that the UIColor class can call the variable like this [UIColor redColor];
How can I write my class to do the same thing? Also, can I have a method only for class, for example, like this:
[MyClass callingMyMethod];
Thank you.
Yes. Just use a + instead of a - when declaring the method:
+ (void)callingMyMethod
{
...
}
You have to create a class method. Class methods are defined like instance method, but have a + instead of a -:
#interface MyClass : NSObject
+ (id)classMethod;
- (id)instanceMethod;
#end
#implementation MyClass
+ (id)classMethod
{
return self; // The class object
}
- (id)instanceMethod
{
return self; // An instance of the class
}
Note that within a class method, the self variable will refer to the class, not an instance of the class.
Yes, they are call class messages. Use + instead of - when defining a message.
Like this:
#interface MyClass : NSObject
{
}
+ (void) callingMyMethod;
Use a + instead of the -. This is called a class method and is used to for initializing and return the object.
#interface SomeClass : NSObject
+ (id)callingMyMethod;
- (id)otherMethod;
#end
#implementation SomeClass
+ (id)callingMyMethod
{
return self; // The class object
}
- (id)otherMethod
{
return self; // An instance of the class
}
Related
I have class tructure like this
#interface SuperClass: NSObject
+ (void) someName;
#end
#interface MyClass: SuperClass
#end
There is the case that i only want to call the someName if it is a class method of MyClass not MyClass's superclass. Since [[MyClass class] respondsToSelector:#selector(someName)] return YES if a class or its super response to the selector. How to tell that MyClass doesnt contain tosomeName?
In my application i want to print the string that contains chains of string return from a class method.
Take abve class structure as a example, i want to print something like:
somenameFromSuper.somenameFromClass.someNameFromeSubClass.
if a class doesnot implement someName method, i want to replace it by `notavailable, for ex:
somenameFromSuper.notavailable.someNameFromeSubClass.
_Bool class_implementsMethodForSelector( Class cls, SEL selector )
{
unsigned methodsCount;
Method* methods = class_copyMethodList(cls, &methodsCount);
for (unsigned methodIndex=0; methodIndex<methodsCount; methodIndex++)
{
if (method_getName(methods[methodIndex]) == selector)
{
break;
}
}
free(methods);
return methodsIndex<methodsCount;
}
…
Class classToTest = …;
classToTest = object_getClass(classToTest); // For checking class methods
if (class_implementsMethodForSelector(classToTest, #selector(someName))
{
…
}
else
{
…
}
Typed in Safari.
Edit: Made a function of it. Still typed in Safari.
i was a beginner in iOS developing.
i was so confused that i get this error.i can simply solve it by changing "[self maxRank]" to "[PlayingCard maxRank]"
but i don't why this happen.
thanks in advance.
this is my code
#import "PlayingCard.h"
#implementation PlayingCard
#synthesize suit=_suit;
+ (NSArray *)validSuits
{
return #[#"♠︎",#"♣︎",#"♥︎",#"♦︎"];
}
+ (NSArray *)validRanks
{
return #[#"?",#"1",#"2",#"3",#"4",#"5",#"6",#"7",#"8",#"9",#"10",#"J",#"Q",#"K"];
}
+ (NSUInteger)maxRank
{
return [[PlayingCard validRanks] count]-1;
}
- (NSString *)suit
{
return _suit?_suit:#"?";
}
- (void)setSuit:(NSString *)suit
{
if ([[PlayingCard validSuits] containsObject:suit]) {
_suit=suit;
}
}
- (void)setRank:(NSUInteger)rank
{
if (rank<=[self maxRank]) { // this is where i get my error
_rank=rank;
}
}
- (NSString *)contents
{
NSArray *rankString=[PlayingCard validRanks];
return [rankString[self.rank] stringByAppendingString:self.suit];
}
#end
#import "Card.h"
#interface PlayingCard : Card
#property (strong, nonatomic)NSString *suit;
#property (nonatomic)NSUInteger rank;
+ (NSArray *)validSuits;
#end
In Objective-C there are two different types of methods:
1. Class Method - denoted by a + before it
Class methods operate on the class itself. Therefore, when you use self in a class method, it refers to the class.
2. Instance Method - denoted by a - before it
Instance methods operate on a specific instance of a class that has been allocated. Therefore, when you use self in an instance method, it refers to the instance of that class.
Your setRank: method is an instance method but maxRank is a class method. When you try to call maxRank on self from setRank:, you are trying to call an instance method named maxRank, which does not exist. If you want to call a class method without specifying the class explicitly, you can use the class property on all instances:
- (void)instanceMethod {
[self.class maxRank];
}
The maxRank method is a class method, not an instance method, so you cannot use "self" with it. If you want maxRank to be a instance method, you need to change the leading + sign to a hyphen (-).
It's because methods with + prefix are class methods, not instance method.
You need to read up on the difference between those.
I have 3 class.
Class A contains :
A static variable "dataX".
A setter method to set the data.
A getter method to return the data value.
Class B
Class C.
the flow is as follows:
The Class B instanciates the Class A and initialize the variable "dataX" with the setter method.
Afterwards, the class C instantiates the Class A in the viewDidLoad method and gets the value of the static variable.
But even if the variable in Class A is static, the variable is always null.
I guess that I need to put the Singleton Pattern with a static Class A and not simply a static attribute.
What is the syntax to specify a Class as Static?
The code below:
// HandleMessage.h
#interface HandleMessage : NSObject
#property *NSString nameFile;
// Getter
- (NSString *)getNameFile;
// Setter
- (void)setNameFile: (NSString *) value;
#end
And:
// HandleMessage.m
#import "HandleMessage.h"
#implementation HandleMessage
static nameFile;
#synthesize nameFile ;
// Getter definition
- (NSString *)getNameFile{
return nameFile;
}
// Setter definition
- (void)setNameFile: (NSString *) value{
nameFile = value;
}
When you instantiate another instance of a class of course this instance's value is null.
You can work with singletons or store your data elsewhere (if you want to keep data between app starts in your user defaults using NSUserdefaults)
what do you mean by "Class as Static"??
you can use singleton pattern, which i described in this answer
or using class method
ClassA.h
#interface ClassA
+ (void)setData:(int)data;
+ (int)getData;
#end
ClassA.m
static int sData;
#implementation ClassA
+ (void)setData:(int)data {
sData = data;
}
+ (int)getData {
return data;
}
#end
Is there a way to call a class method from another method within the same class?
For example:
+classMethodA{
}
+classMethodB{
//I would like to call classMethodA here
}
In a class method, self refers to the class being messaged. So from within another class method (say classMethodB), use:
+ (void)classMethodB
{
// ...
[self classMethodA];
// ...
}
From within an instance method (say instanceMethodB), use:
- (void)instanceMethodB
{
// ...
[[self class] classMethodA];
// ...
}
Note that neither presumes which class you are messaging. The actual class may be a subclass.
Should be as simple as:
[MyClass classMethodA];
If that's not working, make sure you have the method signature defined in the class's interface. (Usually in a .h file)
In objective C 'self' is used to call other methods within the same class.
So you just need to write
+classMethodB{
[self classMethodA];
}
Sure.
Say you have these methods defined:
#interface MDPerson : NSObject {
NSString *firstName;
NSString *lastName;
}
+ (id)person;
+ (id)personWithFirstName:(NSString *)aFirst lastName:(NSString *)aLast;
- (id)initWithFirstName:(NSString *)aFirst lastName:(NSString *)aLast;
#property (copy) NSString *firstName;
#property (copy) NSString *lastName;
#end
The first 2 class methods could be implemented as follows:
+ (id)person {
return [[self class] personWithFirstName:#"John" lastName:#"Doe"];
}
+ (id)personWithFirstName:(NSString *)aFirst lastName:(NSString *)aLast {
return [[[[self class] alloc] initWithFirstName:aFirst lastName:aLast]
autorelease];
}
I have to call an objective C method from a cpp Function.
I have a class C, whose object address is required in this function. I did come across another link which guided me on how to have a reference to the class C, and use it for invocation from the cpp function.
In my case, there is one small difference in that the Class C is already instantiated, and I would not want to allocate an object again. So how can I get its object address?
The code looks like this:
C.h
import Cocoa/Cocoa.h
id refToC
#interface C: NSObject
{
;
somemethod;
;
}
#end
C.m
#implementation C
- (void) somemethod
{
;
;
}
#end
B.mm
import C.h
void func()
{
//I need the address of object here, so as to invoke:
[refToC somemethod];
}
Thanks in Advance
~ps7
The id type is already a pointer to an object. Once you have created a valid object, e.g.:
refToC = [[C alloc] init]
The easiest way is to make use of the singleton design pattern. Here's a common way to make use of that pattern in Objective-C:
Widget.h
#interface Widget : NSObject {
// ...
}
// ...
- (void)someMethod;
+ (Widget *)sharedWidget;
#end
Widget.m
#implementation Widget
// ...
+ (Widget *)sharedWidget {
static Widget *instance;
#synchronized (self) {
if (!instance)
instance = [[Widget alloc] init];
}
return instance;
}
#end
CppWrapper.mm
void methodWrapper() {
[[Widget sharedWidget] someMethod];
}
Thanks a lot for your pointers. I had missed telling that the class C is a controller class. I tried assigning refToC to self in awakeFromNib, and the invocation in func() worked like a charm.
Thanks Matt and John for your pointers.
~ ps7