The equivalent of your java code would be this. The "alloc" is the equivalent of "new" (it reserves the memory) and the init is the constructor that sets the default values.
Some methods - often called "convenience constructors" - return autoreleased obejcts. When you call stringWithString: it DOES call alloc and init, but it will also add the object to the current "autorelease pool" before returning it. You can continue to use that object until the pool is drained (usually at the end of the current event loop iteration) and then it will be destroyed.
Autorelese is a convenient way to create temporary objects that have no "owner" - no one keeping it alive except the autorelease pool. There is no such equivalent in Java, where objects are kept alive until all pointers to it are set to null or fall out of scope.
Actually, sorry, I'm not sure I answered the right question. Are you asking how we can call [NSString anything], since we don't have an instance of NSString yet? That's because alloc and stringWithFormat: are class methods. You have the equivalent in Java, right, with static class methods?
Code:
ClassName.someClassMethodName(args);
In fact you might use a class method to do the same thing in Java without calling "new."
Thanks - you answered both my questions. I'll probably keep this thread alive with future questions and I suspect there are many Java programmers out there who share some of the same questions that I do.
I apologize in advance for this very elementary question but the following piece of code confused me
Code:
NSRange range = [someString rangeOfString:@"some"];
Isn't NSRange a class? Shouldn't we declare a pointer first, then instantiate an object before calling methods on it? I mean if the above is valid then why do we do the following?
Not everything that starts with "NS" is a class. NSRange and NSInteger, for example, are not.
NSRange is a struct; a struct is just a collection of fields, kind of like an object without methods. NSInteger is a kind of int, a primitive type. I know Java has primitive types, but I don't think it has structs.
If you're in doubt you can always control-click a type like NSInteger and it will jump to the definition. Or command-click? I'm not at an apple keyboard. Whichever one is "jump to definition." Eventually you'll just know which are which and you won't have to look it up.
Structs and functions are features of the C programming language, which Objective-C is built on top of. Accessing a struct or a function is faster than accessing an object property or a method, so you still see them poke through in some places.
Thank you very much - this helps a lot. Some of these types definitely are very different from Java and porting my mind from there is taking some time. Thanks for your help - it is much appreciated.