3 ms·
Please understand that to do anything in Objective C you must pass a message to an object.So when we write. MyArray *array = [[MyArray alloc] initWithObjects:@
by freemarketteddy 15y ago
Please understand that to do anything in Objective C you must pass a message to an object.So when we write.
MyArray *array = [[MyArray alloc] initWithObjects:@"string1",@"string2",...];
Lets understand this in two steps:
Step 1) You first allocate an object of type NSArray by passing a message "alloc" to the NSArray Class object.Yes every class in objective C is really a class object in the Objective C runtime.Now this class object may allocate data or it may not.It may also return you a pointer to a previously allocated object(Yes that is a cool way of implementing the singleton pattern.In any case it will return you a pointer to an allocated memory space or nil.
Step 2) Now you tell the allocated object how to initialize itself.The allocated object may have been already initialized and it might just append the strings.The allocated object might be nil.
What I am trying to point out is that there is a lot of dynamism involved in writing an initialization in a two step message passing.It almost feels like the objects are alive.My opinion is that this is real object oriented programming.
- saurik 15y agoThe poster seems to be complaining that there is not similar syntax to many scripting languages, where you can do [@"string1", @"string2"], not about two-phase message allocation; he wasn't complaining for "dictionaryWithConstructorIDontWantToType:", he was complaining against it. In this specific case, you actually can usually use "arrayWithObjects:" (yes, the syntax that the poster didn't like), and it is frankly preferred. If you are doing alloc/init, and (as in your example) storing to a local variable, you should also send an autorelease in the same statement, so as to guarantee exception safety of allocation for subsequent code; "arrayWithObjects:" takes care of all three steps for you.
- freemarketteddy 15y agoYes..arrayWithObjects is definitely a better choice in this case...I was just trying to point out what exactly a line like object = [[[MyClass alloc] initWithObjects:@"",...] autorelease] means...and why it is more powerful than writing object = @"",@"",@"",. Although the latter approach can be taken by using macros ,I was making an argument for the beauty of the first approach.For example it would not be possible to allocate a singleton object with a line like that in Python.