Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa -/+ declarations

What's the difference between - and + when declaring with Cocoa/Obj-C.

e.g. -(void)doSomething{} or +(void)doSomething{}

like image 758
user101248 Avatar asked May 24 '26 23:05

user101248


2 Answers

"-" means an instance method (meaning relative to a specific object), while "+" means a class method (meaning usable by a class in general—it doesn't have to be tied to a specific object).

Example:

For "- (void)doSomething":

MyClass *obj = [[MyClass alloc] init];
[obj doSomething];

vs

[MyClass doSomething];

for "+ (void)doSomething".

like image 51
hbw Avatar answered May 27 '26 12:05

hbw


Just to add a little analogy to htw's answer:

  • + is for what a static method would be in C++, C# or Java
  • - is for what a non-static (regular) method would be in C++, C# of Java
like image 32
Pablo Santa Cruz Avatar answered May 27 '26 13:05

Pablo Santa Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!