I've seen it claimed that the following are "pretty much equivalent":
foo([NSString stringWithString:#"blah"]) # version 1
foo([[[NSString alloc] initWithString:#"blah"] autorelease]) # version 2
Are the above in fact literally equivalent or are there any subtle differences?
What are reasons to prefer one or the other?
They are equivalent, but I prefer "stringWithString" since it is more concise.
The two are functionally equivalent, but as rpetrich observes, may operate ever-so-slightly differently internally. This shouldn't matter to you, use whichever seems more convenient to you. Furthermore, while there is a minute performance difference, it is highly unlikely to matter to your application in practice.
But all this misses a crucial point: both are pointless. By writing #"foo" you already have a fully functional NSString object. There is no need to mess around with extra methods to duplicate the string; it is quicker and simpler to just do:
foo(#"blah")
In most cases, the only difference is an extra call to objc_msgSend.
Decompiling NSString reveals that instead of sending +alloc it sends +allocWithZone:NSDefaultMallocZone()
Methods such as +stringWithString: or +array are simply convenience methods which always return autoreleased objects. These are mostly in place to reduce the amount of code written for classes that are created often, such as strings, arrays, dictionaries, numbers, etc. They strictly follow the basic memory management rules from which the one I mentioned above are derived.
Related
Is there any reason to use NSClassFromString instead of objc_getClass, assuming that I don't already have an NSString * (i.e. just choosing which type of string literal to write)? My assumption is that NSClassFromString calls objc_getClass anyways, so it's slightly more efficient to use the runtime function.
NSClassFromString is a higher-level function than objc_getClass, which as you say, is more convenient due to the fact that it takes an NSString. So objc_getClass should be fine. With that said, if performance is a major concern, Objective-C runtime hackery isn't usually the best way to achieve it.
In this case you are better off optimising for your own usability/readability and using the higher level NSClassFromString. The lower level APIs will be more awkward to use (especially from Swift) and will look out of place in amongst all your other app code that's written in Objective-C/Swift.
I wouldn't worry about efficiency too much unless you find you have performance issues and can track it back to using this function (very unlikely).
what is the difference between these two approaches for objection creation?
NSNumber *aInt= #54;
NSNumber *aInt= [NSNumber numberWithInt:54];
I know that first approach is NSNumber literal and second is NSNumber class methods. Both are used to create an NSNumber object. But which approach is better?
if i creates object using literal style then how memory is allocated to it? How it is differ then second approach? Please suggest me some key point about these concepts so that i prefer better approach to create NSNumber object.
I know that object created at runtime. Does literals objects are also created at runtime? please provide some essential key points to clear my doubt.
They are identical. In fact they are translated to the same code during compilation.
I always go for the literal because it's easier to read.
What is the difference between these two approaches for objection
creation?
They are Identical.
Answers for:
No. 1:
Using #-prefix will automatically wrap scalar types like int or float.
No. 2:
Using numberWith[type] creates NSNumber specifically and therefor easy to distinguish.
I'm not really sure about memory management of it, but i think, talking about memory allocation it's just the same.
I personally use numberWith[type] because it's more distinguishable (for me), i mean the types it holds and i dont have to worry about backward compatibility, but still i have the knowledge about the literals so i dont have any issue using it.
Better approach is very hard to answer, it's completely up to you/to the developer.
You might also want to check this link
And please, avoid asking too many questions in one post. Cheers! :)
This question is just out of curiosity but, how is NSSet implemented? What data structure is behind it and what are the access times for adding and removing elements? If I had to guess, I'd say it was some sort of hashtable/dictionary data structure, but in that case why differentiate between NSSet and NSMutableSet?
Well, as Bavarious pointed out in a comment, Apple's actual CoreFoundation source is open and available for your perusal too. NSSet is implemented on top of CFSet, whose code is generated (as is that of CFDictionary) from a hash table template, using CFBasicHash to do the work.
The difference between mutablility and immutability seems to be the matter of a flag in the structure (line 91 of CFBasicHash.h), and from my reading so far just affects calls to functions such as CFBasicHashAddValue; there's a simple check for the mutability. It seems likely, however, that Cobbal is right about the copy/retain behavior between the two (I just haven't read that far yet).
PREVIOUSLY:
I find it interesting and educational occasionally to peruse the GNUstep sources when I'm wondering about implementation details. They are, of course, not at all guaranteed to be implemented the way that Apple did it, but they can be helpful in some cases. Their version of Foundation: http://gnu.ethz.ch/debian/gnustep/gnustep-base-1.20.0/Headers/Foundation/ (I hope that's the most recent version. If not, someone please correct me.)
To answer the second half of your question: one benefit of having a non-mutable version is that it allows for a very fast copy method that simply calls retain.
I find this link to be an interesting answer to your question. Apple's data structures (NSArray, NSSet, NSDictionary, etc.) are not implemented in a straightforward and "standard way." In most cases, they perform in the same way any other set would perform, but overall, they optimize automatically for the best performance. So, in truth, it's rather difficult to say. While Apple provides documentation on the efficiency of arrays in CFArray.h (equivalent for NSArrays), it offers no such documentation on the efficiency of sets, though you're free to poke around /System/Library/Frameworks/CoreFoundation.framework/Headers/ to look through other data structure implementations.
In addition, there has to be a distinction between a set and its mutable counterpart, just as there is a distinction between NSString and NSMutableString, NSArray and NSMutableArray, and NSDictionary and NSMutableDictionary (among others). For data structures and strings (and few other classes), Apple offers 'readonly' versions of classes to retain generality, along with standard 'mutable' counterparts for manipulation. It's simply Apple's standard practice.
In Objective-C, you can't declare method names where the last component doesn't take an argument. For example, the following is illegal.
-(void)take:(id)theMoney andRun;
-(void)take:(id)yourMedicine andDontComplain;
Why was Objective-C designed this way? Was it just an artifact of Smalltalk that no one saw a need to be rid of?
This limitation makes sense in Smalltalk, since Smalltalk doesn't have delimiters around message invocation, so the final component would be interpreted as a unary message to the last argument. For example, BillyAndBobby take:'$100' andRun would be parsed as BillyAndBobby take:('$100' andRun). This doesn't matter in Objective-C where square brackets are required.
Supporting parameterless selector components wouldn't gain us much in all the usual ways a language is measured, as the method name a programmer picks (e.g. runWith: rather than take:andRun) doesn't affect the functional semantics of a program, nor the expressiveness of the language. Indeed, a program with parameterless components is alpha equivalent to one without. I'm thus not interested in answers that state such a feature isn't necessary (unless that was the stated reasons of the Objective-C designers; does anyone happen to know Brad Cox or Tom Love? Are they here?) or that say how to write method names so the feature isn't needed. The primary benefit is readability and writability (which is like readability, only... you know), as it would mean you could write method names that even more closely resemble natural language sentences. The likes of -(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication*)theApplication (which Matt Gallagher points out on "Cocoa With Love" is a little bit confusing when you drop the formal parameter) could be named -(BOOL)application:(NSApplication*)theApplication shouldTerminateAfterLastWindowClosed, thus placing the parameter immediately next to the appropriate noun.
Apple's Objective-C runtime (for example) is perfectly capable of handling these kind of selectors, so why not the compiler? Why not support them in method names as well?
#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#interface Potrzebie : NSObject
-(void)take:(id)thing;
#end
#implementation Potrzebie
+(void)initialize {
SEL take_andRun = NSSelectorFromString(#"take:andRun");
IMP take_ = class_getMethodImplementation(self, #selector(take:));
if (take_) {
if (NO == class_addMethod(self, take_andRun, take_, "##:#")) {
NSLog(#"Couldn't add selector '%#' to class %s.",
NSStringFromSelector(take_andRun),
class_getName(self));
}
} else {
NSLog(#"Couldn't find method 'take:'.");
}
}
-(void)take:(id)thing {
NSLog(#"-take: (actually %#) %#",NSStringFromSelector(_cmd), thing);
}
#end
int main() {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
Potrzebie *axolotl=[[Potrzebie alloc] init];
[axolotl take:#"paradichloroaminobenzaldehyde"];
[axolotl performSelector:NSSelectorFromString(#"take:andRun")
withObject:#"$100"];
[axolotl release];
[pool release];
return 0;
}
This is Brad Cox. My original answer misunderstood the question. I assumed reallyFast was a hardcoded extension to trigger faster messaging, not a kind of syntactic sugar. The real answer is that Smalltalk didn't support it, perhaps because its parser couldn't deal with the (assumed) ambiguity. Although OC's square brackets would remove any ambiguity, I simply didn't think of departing from Smalltalk's keyword structure.
21 years of programming Objective-C and this question has never crossed my mind. Given the language design, the compiler is right and the runtime functions are wrong ().
The notion of interleaved arguments with method names has always meant that, if there is at least one argument, the last argument is always the last part of the method invocation syntax.
Without thinking it through terribly much, I'd bet there are some syntactic bugaboos with not enforcing the current pattern. At the least, it would make the compiler harder to write in that any syntax which has optional elements interleaved with expressions is always harder to parse. There might even be an edge case that flat out prevents it. Certainly, Obj-C++ would make it more challenging, but that wasn't integrated with the language until years after the base syntax was already set in stone.
As far as why Objective-C was designed this way, I'd suspect the answer is that the original designers of the language just didn't consider allowing the interleaved syntax to go beyond that last argument.
That is a best guess. I'll ask one of 'em and update my answer when I find out more.
I asked Brad Cox about this and he was very generous in responding in detail (Thanks, Brad!!):
I was focused at that time on
duplicating as much of Smalltalk as
possible in C and doing that as
efficiently as possible. Any spare
cycles went into making ordinary
messaging fast. There was no thought
of a specialized messaging option
("reallyFast?" [bbum: I asked using 'doSomething:withSomething:reallyFast'
as the example]) since ordinary
messages were already as fast as they
could be. This involved hand-tuning
the assembler output of the C
proto-messager, which was such a
portability nightmare that some if not
all of that was later taken out. I do
recall the hand-hacked messager was
very fast; about the cost of two
function calls; one to get into the
messager logic and the rest for doing
method lookups once there.
Static typing enhancements were later
added on top of Smalltalk's pure
dynamic typing by Steve Naroff and
others. I had only limited involvement
in that.
Go read Brad's answer!
Just for your information, the runtime doesn't actually care about the selectors, any C string is valid, you could as well make a selector like that: "==+===+---__--¨¨¨¨¨^::::::" with no argument the runtime will accept it, the compiler just can't or else it's impossible to parse. There are absolutely no sanity check when it comes to selectors.
I assume they are not supported in Objective-C because they weren't available in Smalltalk, either. But that has a different reason than you think: they are not needed. What is needed is support for methods with 0, 1, 2, 3, ... arguments. For every number of arguments, there is already a working syntax to call them. Adding any other syntax would just cause unnecessary confusion.
If you wanted multi-word parameterless selectors, why stop with a single extra word? One might then ask that
[axolotl perform selector: Y with object: Y]
also becomes supported (i.e. that a selector is a sequence of words, some with colon and a parameter, and others not). While this would have been possible, I assume that nobody considered it worthwhile.
I want to perform the same action over several objects stored in a NSSet.
My first attempt was using a fast enumeration:
for (id item in mySetOfObjects)
[item action];
which works pretty fine. Then I thought of:
[mySetOfObjects makeObjectsPerformSelector:#selector(action)];
And now, I don't know what is the best choice. As far as I understand, the two solutions are equivalent. But are there arguments for preferring one solution over the other?
I would argue for using makeObjectsPerformSelector, since it allows the NSSet object to take care of its own indexing, looping and message dispatching. The people who wrote the NSSet code are most likely to know the best way to implement that particular loop.
At worst, they would simply implement the exact same loop, and all you gain is slightly cleaner code (no need for the enclosing loop). At best, they made some internal optimizations and the code will actually run faster.
The topic is briefly mentioned in Apple's Code Speed Performance document, in the section titled "Unrolling Loops".
If you're concerned about performance, the best thing to do is set up a quick program which performs some selector on the objects in a set. Have it run several million times, and time the difference between the two different cases.
I too was presented with this question. I find in the Apple docs "Collections Programming Topics" under "Sets: Unordered Collections of Objects" the following:
The NSSet method objectEnumerator lets
you traverse elements of the set one
by one. And
themakeObjectsPerformSelector: and
makeObjectsPerformSelector:withObject:
methods provide for sending messages
to individual objects in the set. In
most cases, fast enumeration should be
used because it is faster and more
flexible than using an NSEnumerator or
the makeObjectsPerformSelector:
method. For more on enumeration, see
“Enumeration: Traversing a
Collection’s Elements.”
This leads me to believe that Fast Enumeration is still the most efficient means for this application.
I would not use makeObjectsPerformSelector for the simple reason that it is the kind of call that you don't see all that often. Here is why for example - I need to add debugging code as the array is enumerated, and you really can't do that with makeObjectsPerformSelector unless you change how the code works in Release mode which is a real no no.
for (id item in mySetOfObjects)
{
#if MY_DEBUG_BUILD
if ([item isAllMessedUp])
NSLog(#"we found that wily bug that has been haunting us");
#endif
[item action];
}
--Tom
makeObjectsPerformSelector: might be slightly faster, but I doubt there's going to be any practical difference 99% of the time. It is a bit more concise and readable though, I would use it for that reason.
If pure speed is the only issue (i.e. you're creating some rendering engine where every tiny CPU cycle counts), the fastest possible way to iterate through any of the NSCollection objects (as of iOS 5.0 ~ 6.0) is the various "enumerateObjectsUsingBlock" methods. I have no idea why this is, but I tested it and this seems to be the case...
I wrote small test creating collections of hundreds of thousands of objects that each have a method which sums a simple array of ints. Each of those collections were forced to perform the various types of iteration (for loop, fast enumeration, makeObjectsPerformSelector, and enumerateObjectsUsingBlock) millions of times, and in almost every case the "enumerateObjectsUsingBlock" methods won handily over the course of the tests.
The only time when this wasn't true was when memory began to fill up (when I began to run it with millions of objects), after which it began to lose to "makeObjectsPerformSelector".
I'm sorry I didn't take a snapshot of the code, but it's a very simple test to run, I highly recommend giving it a try and see for yourself. :)