-2

I'm reading a book for learning Objective-c but I didn't understand this code:

NSString* myString = [NSString string];

I know if you typed [ object method ] or object.method that the method inside the class will be called, but what does [ Class method ] means ?

Luwe
  • 3,026
  • 1
  • 20
  • 21

4 Answers4

1

[Class method] is a class method.

Read the documentation for more detail.

By the way, you don't write object.method in Objective-C. The dot syntax is used only to access or set properties of an object.

DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • Oh thanks u answered my second question no need for write it now thanks :) – user3267672 Sep 15 '12 at 22:02
  • By the way, you **can** write `object.method`.... And it even does the same thing. – lnafziger Sep 15 '12 at 22:17
  • Only because it compiles, it doesn't mean it's good practice. The dot syntax in Objective-C isn't used for methods, just for @properties. In fact, if you try to do something like `object.method;` you get a warning *Property access result unused - getters should not be used for side effects* – DrummerB Sep 15 '12 at 22:49
0

It's a class method - it's basically a method that is called on the class itself and not on a particular instance (object) of a class. See this question for further explanation.

Community
  • 1
  • 1
  • Thanks A lot but when will i need to write +(void)myClassMethod and whem do i need to write -(void)myInstanceMethod i am sorry if it was written in the code that u sent to me but maybe i didint noticed it – user3267672 Sep 15 '12 at 22:10
  • @Omar + is for class methods, - is for instance methods. **read an Objective-C turorial. Now.** –  Sep 15 '12 at 22:28
0

The first line creates a new, empty string. Length 0. It's just @"". You can accomplish the same thing by NSString *myString = @""; Class vs Instances is the last question you have. Class is the "I want to make what this method gives me". If you are using [NSString string], then essentially you are doing [[NSString alloc] init]. So, the instance gives you access to methods and variables that are for your Class instance (aka myString), so [myString length]. You can't do [NSString length].

Class methods are the interface to getting an instance (or getting the class type), and instance methods are for the in memory instance of that class that you are actually using.

Sorry for the convoluted answer.

Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281
jheld
  • 148
  • 2
  • 8
0

As you might know you there aren't only methods that you can send to instances of a class. There are also methods you can send to the class object of a method. This specific method returns an empty string and gives it to "myString". For further information on class objects read the Apple Document "The Objective-C Programming Language"

Jörg Kirchhof
  • 1,530
  • 1
  • 9
  • 19