-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 ?

4

4 回答 4

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.

于 2012-09-15T21:52:35.827 回答
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.

于 2012-09-15T21:51:27.597 回答
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.

于 2012-09-15T21:54:14.790 回答
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"

于 2012-09-15T21:54:21.457 回答